0

I went through lot of the resources on web but still not able to get this. I didn't understand how std::skipws works to ignore whitespaces , tabs and newlines.

Following is my simple code

vector<string> vec;
while(1){

    getline(cin, s); 

    if( s.compare("#") == 0)
        break;
    else
        vec.push_back(s);
}   

I will enter a line of strings with newlines, whitespaces and tabs. After input I want to store strings into the vector and that will stop when "#" string is encountered. I tried with the above code but it store spaces along with the strings in the vector though it terminates after enterting "#".

cbinder
  • 2,388
  • 2
  • 21
  • 36

2 Answers2

2

The purpose of std::getline is to read an entire line, including whitespace, into a string buffer.

If you want to read tokens from a stream, skipping whitespace, then use the standard input operator >>.

std::vector<std::string> vec;
std::string s;
while(std::cin >> s && s != "#") {
    vec.push_back(s);
}

Live example

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
0

std::skipws is skipping only the leading whitespace characters in any input stream. It therefore has no effect on all the whitespaces after the first non-whitespace. If you want to read whole lines with getline(cin, s) you might as well consider removing the blanks and tabs that have been read from the string before pushing it into the container like so :

while (1){
    getline(cin, s);
    if (s.compare("#") == 0) {
        break;
    }
    else {
        s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
        vec.push_back( s );
    }
} 

For a discussion on how to remove whitespaces from a string see also : Remove spaces from std::string in C++

Community
  • 1
  • 1
Angle.Bracket
  • 1,438
  • 13
  • 29