Search code examples
c++stringstreamiostreamseparator

How to separate strings in an istream only by '\n'?


Given a file that contains a string "Hello World" (Note that there is a space between 'Hello' and 'World').

int main()
{
    ofstream fout("test.txt");
    fout.write("Hello World", 12);
    fout.close();

    ifstream fin("test.txt");
    vector<string> coll((istream_iterator<string>(fin)),
                        (istream_iterator<string>()));
    // coll contains two strings 'Hello' and 'World' rather than 
    // one string "Hello World" that is just I want.
}

In other words, I want that strings in an istream should only be separated by '\n' rather than ' ', '\n', etc.

How should I do?


Solution

  • Use std::getline(std::cin,str) instead. The third parameter does what you want, and it defaults to '\n'. Alternatively you can disable skipping whitespace by setting passing std::cin >> std::noskipws >> str or turn off the flag completely by doing std::cin.unsetf(std::ios::skipws)