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

如果我输入tt tt tt,则输出为tt tt tt。 但是,如果我什么都没输入,我输入Ctrl + Z(windows + vs2013)会崩溃。 所以我尝试修复它。如果我输入“Ctrl + Z”,它会崩溃,如何修复它?

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

现在,如果我输入什么,我键入按Ctrl +ž不会崩溃。 但是,如果我输入tt tt tt,输出是tt tt tt tt

现在我不知道如何解决它。请帮帮我 。

+1

做您使用调试器来查看它崩溃的位置?也使用stringstream而不是'std :: cin'可能是一个好主意,你可以用EOF填充stringstream。另见http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – holgac 2015-03-03 07:57:07

+0

'&&!cin.eof()'是多余的。 'operator >>'将返回流对象,当它到达EOF时,流对象的计算结果为'false'。 – 2015-03-03 08:21:17

回答

1

你应该尝试只是:

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

为什么额外TT
如果我解开你的while循环,这是不言而喻的:

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 

您还可以阅读Why while(!feof(...)) is almost always wrong

+0

我在vs2013中试过了你的代码,如果我没有输入,然后输入'ctrl + z',它仍然会崩溃,那么你能给我其他建议吗? – Ocxs 2015-03-03 12:04:37

+0

你可以尝试'do {if(cin >> str)svec.push_back(str);} while(!cin.eof())''。尽管我认为额外检查是多余的,您应该尝试找出崩溃的来源。 – 2015-03-03 12:12:10

+0

我试过了,它也坠毁了。如果我在'while'中使用'!cin.eof()'(而不是'do {} while'),它不会崩溃。但作为你的[链接](http://stackoverflow.com/questions/5431941/ while-feof-file-is-always-wrong)说,**它比作者期望的多一次进入循环。如果有读取错误,循环不会终止。**。如果我不使用cin.eof(),它会崩溃。 – Ocxs 2015-03-03 12:32:06

相关问题