Ctrl+Z结束输入的问题
[code=C/C++][/code]
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> words;
string temp;
while(cin>>temp)
words.push_back(temp);
cout<<"number of words"<<words.size()<<endl;
}
当输入:aa dd ss ctrl+Z 时,不能用Ctrl+Z来结束输入,必须在回车之后在按Ctrl+Z来结束
这是为什么???
[解决办法]
因为标准C++ I/O函数是有缓冲的,你输入aa dd ss ctrl+z之后,cin调用read读到aa dd ss到缓冲中,返回aa给用户,再次调用直接返回dd,再次调用直接返回ss,从而忽略掉了ctrl+z,因为第一次read把它带过了。此刻调用cin,因为缓冲区空,于是read阻塞等待输入,你输入ctrl+z,read返回0,于是cin>>调用立即返回,cin状态为eof,while退出。
[解决办法]
[Quote=引用:]
[code=C/C++][/code]
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> words;
string temp;
while(cin>>temp)
words.push_back(temp);
cout<<"number of wo……
[/Quote]
这是windows的观念,不是代码问题,不同操作系统是不同的。
windows认为,如果缓冲中还有其它内容,ctrl+z不表示输入结束,仅代表当前行输入结束,只在单独一个ctrl+z的时候才表示输入结束。