so I'm taking in input by
string input,word;
while(getline(cin, input)) {
stringstream ss;
ss<<input
while(ss >> word)
...
and printing the stuff I want by
cout <<word<<" ";
However, when I do this it creates an extra whitespace at the end of each line and I don't want that. If I don't put that whitespace there there will be no spaces between words when I print them out. Is there an easier way to cout the words I want so that they are automatically spaced? What are some of the things I could do to prevent the extra whitespace at the end of each line.
Test the first word extraction outside the loop, then continue the loop with leading spaces:
std::string input;
while(getline(std::cin, input))
{
std::istringstream ss(input);
std::string word;
if (ss >> word)
{
std::cout << word;
while (ss >> word)
std::cout << ' ' << word;
std::cout << '\n';
}
}
Note: newline added for line completion. Use or delete at your discretion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With