退出while循环,cin.使用ctrl-Z/ctrl-D无法使用c++
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而不是键入quit或其他内容。
我解决了自己的问题。问题是,我以前使用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())
。
相关文章:
- 热键/按钮,根据需要进行编译,但不运行(在F5和Ctrl+Shift+B之间)
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- Ctrl + 不适用于在 Visual Studio 中运行该程序
- C++键盘挂钩 CTRL 键卡住
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 如果 I/O read() 处于阻塞阶段,如何使用 Ctrl+C 退出 C++ 程序?
- 如何让 getc(stdin) 返回 ctrl 字符?
- 在 ov5640 上使用 V4L2 设置 ctrl
- Ncurses CTRL + s hangs getch()
- C++CTRL+C处理程序有未定义的行为
- 如果输入缓冲区不为空,请使用getchar.()检测Ctrl+d
- Qt 键按事件处理程序仅在按下 ctrl、alt 或 shift 键时做出反应
- 我的控制台处理程序不处理 CTRL+C,即使设置正确
- 当用户在键盘上按住 CTRL 键时,如何在树视图中的 Qt 中实现多选?
- 使用 ctrl + C 在 python 中杀死C++进程
- C++ 上的 SendInput 不接受 Ctrl 和 Shift 帐户
- 如何在我的 Windows 应用程序中捕获按下和释放的 CTRL 键?
- while( scanf( "%d" , &n) ) { ... } 在 Linux 上按 Ctrl+D 时不退出
- C :使用文件末端(CTRL Z)结束一个循环似乎打破了我程序的其余部分
- 用于"Ctrl + left arrow"和"Ctrl + right arrow"的八进制代码