Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent from printing extra whitespace at the end of my line C++

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.

like image 221
Gui Montag Avatar asked Mar 12 '23 02:03

Gui Montag


1 Answers

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.

like image 51
WhozCraig Avatar answered Mar 15 '23 22:03

WhozCraig