Your code segfaults on single-letter words for me.
Also, you should seed the rng so it's different each run.
random_shuffle() uses rand() so you seed it with srand().
Code:
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
string word;
bool done = false;
while (!done && cin >> word) {
auto last = word.end() - 1;
if (ispunct(*last)) {
done = (*last == '.' || *last == '?' || *last == '!');
--last;
}
auto dist = distance(word.begin()+1, last);
if (dist == 2) // always swap middle letters of 4-letter words (maybe?)
swap(word.begin()[1], last[-1]);
else if (dist > 2)
random_shuffle(word.begin()+1, last);
cout << word << ' ';
}
cout << '\n';
return 0;
}
random_shuffle() has been removed from C++ since C++17.
You can use shuffle() instead which uses the <random> library instead of rand().
Code:
#include <algorithm>
#include <iostream>
#include <random>
#include <string>
#include <cctype>
using namespace std;
int main()
{
random_device rd;
minstd_rand g(rd());
string word;
bool done = false;
while (!done && cin >> word) {
auto last = word.end() - 1;
if (ispunct(*last)) {
done = (*last == '.' || *last == '?' || *last == '!');
--last;
}
auto dist = distance(word.begin()+1, last);
if (dist == 2) // always swap middle letters of 4-letter words (maybe?)
swap(word.begin()[1], last[-1]);
else if (dist > 2)
shuffle(word.begin()+1, last, g);
cout << word << ' ';
}
cout << '\n';
return 0;
}