我有一个while循环和代码下面退出一个while循环,cin。使用CTRL-Z/CTRL-d不工作C++
string namn, word;
while(getline(cin, namn)){
istringstream iss(namn);
vector<string> v;
while(iss >> word){
v.push_back(word);
}
for(auto elements: v){
cout << elements << endl;
}
}
cout << "do something" <<endl;
当我运行该代码的循环工作正常,但使用CTRL-Z我不能退出循环(在窗)
我自己也尝试下面这样:
int main(){
string namn;
string pris;
string antal;
vector<string> v;
while(cin >> namn >> pris >> antal){
v.push_back(namn);
v.push_back(pris);
v.push_back(antal);
}
// do something with the vector maybe print it
// i can not exit the loop and continue here
return 0;
}
我也曾尝试第三解决方案,但它不工作之一:
int main(){
string name;
vector<string> v;
while(!cin.eof()&& cin.good()){
cin >> name;
v.push_back(name);
}
// after exiting the loop with ctrl-Z (in windows, ctrl-d in linux)
// do something with the vector, but it never goes here
}
我正在做的或即将解决的任务是您有多行输入,例如名称,价格,金额。那么我将把这些物品存储在一个矢量中。退出应该与使用ctrl-z不打字退出或其他。
您是否在ctrl-z之后按回车键?尝试添加一个中断,如果namn.empty()以空行退出循环。 –