1
    vector<string> svec;
    string str;
    while (cin >> str&&!cin.eof())
    {
        svec.push_back(str);
    }
    for (auto c:svec)
    {
        cout << c << " ";
    }

If I input tt tt tt,the output is tt tt tt. But if i input nothing ,i type Ctrl+Z ( windows + vs2013)will crash. So i try to fix it.

 while (!cin.eof())
    {
        cin >> str;
        svec.push_back(str);
    }

Now , if i input nothing , I type Ctrl+Z will not crash. But if i input tt tt tt,the output is tt tt tt tt.

Now I don't know how to fix it. Please help me .

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Ocxs
  • 149
  • 2
  • 10
  • 1
    did you use a debugger to see where it crashes? also using a stringstream instead of `std::cin` might be a good idea, in which you fill stringstream with EOF. also see http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – holgac Mar 03 '15 at 07:57
  • `&&!cin.eof()` is redundant. `operator>>` will return the stream object, which evaluates to `false` when it reaches EOF. – The Paramagnetic Croissant Mar 03 '15 at 08:21

1 Answers1

1

You should try just:

while (cin >> str)
{
    svec.push_back(str);
}

Why extra tt
If I unroll your while loop, it goes as:

1. buf [tt tt tt, not eof], vec []
  a. is eof no
  b. read and push str
2. buf [tt tt, not eof], vec [tt]
  a. is eof no
  b. read and push str
3. buf [tt, not eof], vec [tt tt]
  a. is eof no
  b. read and push str
4. buf [, not eof], vec [tt tt tt]
  a. is eof no
  b. read and push str [read fails, str contains old value and eof is set]
5. buf [eof], vec [tt tt tt tt]
  a. is eof yes
  b. break

You can also read Why while(!feof(...) ) is almost always wrong

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • I tried your code in vs2013, it still crashed if i input nothing and then typed `ctrl + z`,so can you give me other advice ? – Ocxs Mar 03 '15 at 12:04
  • You can try `do { if(cin >> str) svec.push_back(str);} while (!cin.eof())`. Although I think extra check is redundant and you should try to locate the source of crash. – Mohit Jain Mar 03 '15 at 12:12
  • I tried ,it's also crashed . If I use `!cin.eof()`in `while`(not in `do{}while`),it will not crashed .But as your [link](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)say,**it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.**.If I don't use `cin.eof()`,it will crash. – Ocxs Mar 03 '15 at 12:32
  • I checked the location of crash and fixed it . Thank you very much! – Ocxs Mar 03 '15 at 12:51