Mahmud Adam Mahmud Adam - 2 months ago 15
C++ Question

Sorting words on same line in file using sort()

Is there a way to sort words alphabetically that appear on the same line? I know that if I have words on a new line I am able to sort them easily using:

vector<string> file;
string line;
file.clear();
ifstream infile("foo.txt", ios_base::in);
infile.seekg(3);
while (getline(infile, line)){
file.push_back(line);
}
sort(file.begin(), file.end());
ofstream outFile;
outFile.open("foo.txt");
for (const auto &e : file) outFile << e << "\n";


But what if the words were on one line in the file (unseparated by spaces), for example:
catapebat
(cat ape bat). Is there an easy way to do this in C++? Would I not do the
getline
bit, since I am only grabbing one line? How would I approach this problem?

Answer
  1. Use getline to read a line.
  2. Create an istringstream from the string you just read
  3. Read words from there into a vector<string>
  4. Sort the words in that vector