-2

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?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

3 Answers3

5

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)

Rapptz
  • 20,807
  • 5
  • 72
  • 86
2

To read a line from ifstream, you could use std::getline. Default delimiter of std::getline is \n

int main(int argc, const char * argv[])
{
    ifstream fin("test.txt");
    std::string str;

    while (std::getline(fin, str))
    {
        cout << str << endl;
    }

    return 0;
}
billz
  • 44,644
  • 9
  • 83
  • 100
1
string str;
while(fscanf(fin,"%s\n",&str));
spin_eight
  • 3,925
  • 10
  • 39
  • 61