You are not handling the case when operator>>
fails to read a word once the end of the istringstream
has been reached, thus leaving your word
variable empty. You are outputting the word
before checking if the read was actually successful. That is why you end up with a blank word at the end of your output. You would need to check for that condition, eg:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
istringstream ss(str);
do {
string word;
if (!(ss >> word)) break;
cout << word << ", ";
}
while (true);
}
Alternatively:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
istringstream ss(str);
string word;
while (ss >> word)
{
cout << word << ", ";
}
}
However, either approach would still leave you with a trailing comma at the end of the last word.
You could use a variable to control when the comma is output, eg:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
istringstream ss(str);
string word;
bool first = true;
while (ss >> word)
{
if (first)
first = false;
else
cout << ", ";
cout << word;
}
}
But, in this situation, it would be cleaner to simply output the first word by itself, and then enter a loop to output the remaining words prefixed by a comma, eg:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
istringstream ss(str);
string word;
if (ss >> word)
{
cout << word;
while (ss >> word)
{
cout << ", " << word;
}
}
}