0

I am trying to output a string that I have previously read using cin>>input until EOF. The problem that I am facing is that after I output the string there is no new line when asking for the next string. I already tried using getline(), but the problem was that it was not skipping whitespaces. Any clues ?

#include <iostream>
#include <string>
    
using namespace std;
    
int main()
{
    string input;
    while (cin>>input)
    {
        cout<<input;
    }
    
    return 0;
}

Here is an example :

Input:test test

Output: test test

Input:test test... (Previous input remains in stdin)

Sorry in advance if this is a duplicate, but I could not find anything similar.

Community
  • 1
  • 1
alex01011
  • 1,670
  • 2
  • 5
  • 17
  • 3
    The new line character (`\n`) is not part of the `input`. You need to append it yourself. – ChrisMM Feb 21 '20 at 18:23
  • I get your point, but wouldn't that add a new line for each string I input? For example if the string is test test, test \n test \n will be the output – alex01011 Feb 21 '20 at 18:28
  • 1
    Yes. In that case, you'd probably want to use `getline`, and remove the whitespaces yourself. – ChrisMM Feb 21 '20 at 18:29
  • 1
    `std::getline` and `std::`stringstream` work well together. See [Option 2 of this answer](https://stackoverflow.com/a/7868998/4581301). Since all streams present a shared interface, this trick will work for `cin` just like it does a file. – user4581301 Feb 21 '20 at 18:34

0 Answers0