-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
  • 37,882
  • 21
  • 139
  • 300

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,187
  • 4
  • 71
  • 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
  • 43,318
  • 8
  • 77
  • 98
1
string str;
while(fscanf(fin,"%s\n",&str));
spin_eight
  • 3,847
  • 10
  • 37
  • 60