Mahmud Adam Mahmud Adam - 5 months ago 47
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;
ifstream infile("foo.txt", ios_base::in);
while (getline(infile, line)){
sort(file.begin(), file.end());
ofstream outFile;"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:
(cat ape bat). Is there an easy way to do this in C++? Would I not do the
bit, since I am only grabbing one line? How would I approach this problem?

  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