![](/img/trans.png)
[英]while (cin >> *pchar) awaits further input after Ctrl-Z
[英]exit a while loop , cin . using ctrl-Z/ctrl-D not working c++
我有一个while循环和下面的代码
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 (在 Windows 中)退出循环。
我也在下面试过这个:
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而不是输入退出或其他东西。
我解决了我自己的问题。 问题是我之前使用istringstream
并将其切换到stringstream
,现在退出ctrl - z / ctrl - d工作。
Firstclass myclass;
string item, data;
vector<string> split_input;
// reads in on line of string until ctrl-z/ctrl-d
while(getline(cin, data)){
stringstream str_stream(data);
// reading the values separate adding them to vector
while(str_stream >> item{
split_input.push_back(item);
}
// if amount is not given
if(v.size() == 2){
myclass.insert_data(split_input[0], stod(split_input[1]), 1.00);
}
// if if amount is given
else{
myclass.insert_data(split_input[0], stod(split_input[1]), stod(split_input[2]));
}
// clearing the vector
split_input.clear();
}
显然, std::basic_ios::operator bool()
返回流是否失败,它与!eof()
。 您可能必须将条件更改为while(cin >> namn >> pris >> antal && !cin.eof())
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.