This should fix it:
#include
#include
#include
using namespace std;
int main() {
string str;
getline(cin, str);
string word;
istringstream ss(str);
bool firstIteration = true;
while(ss >> word) {
if(!firstIteration) {
cout << ", ";
}
cout << word;
firstIteration = false;
};
}
Check the working demo here please.
I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:
empty output
firstIteration = true
foreach item in list
if firstIteration
add delimiter to output
add item to output
firstIteration = false
In some cases one could even omit the firstIteration
indicator variable completely:
empty output
foreach item in list
if not is_empty(output)
add delimiter to output
add item to output