getline 一直在等待标准输入
getline keeps waiting on standart input
所以从昨天开始我就一直在纠结这个问题,我检查了这里的多篇帖子试图解决这个问题,基本上,我试图从标准输入中读取 1 行或更多行到字符串变量,然后使用 istringstream 获取整数值。这就是我所拥有的:
string line;
int num;
while(getline(cin, line)){
istringstream data(line);
while(data >> num){
do stuff...
}
}
然而,外层循环永远不会退出,如果标准输入中没有输入,它只是坐在那里等待,永远不会真正退出循环,所以程序基本上会暂停,直到输入内容,然后继续循环再一次。有人能告诉我为什么 getline 在 stdin 上没有任何内容时不只是导致退出条件吗?有人能帮我解决这个问题吗?您的帮助将不胜感激。
if there is no input in the standard input it just sits there waiting and never actually exits the loop, so the program basically pauses until something is entered, and then just continues the loop once more. Can someone tell me why getline doesn't just cause an exit condition when there is nothing on stdin
它的行为符合预期。 "nothing on stdin" 实际上是什么?你的意思是一个空的输入?在这种情况下,您可能希望将循环条件更改为
while(getline(cin, line) && !line.empty()){
也如评论中所述CTRL-Z或CTRL-D(取决于OS)后跟ENTER 输入可能会结束循环。
问题是标准输入 (cin) 将读取一行,并且由于 getline 返回 'true'(引用 != 0),循环将永远继续请求另一行。
如果你想从输入中读取一行,你应该避免 while:
string line;
int num;
getline(cin, line)){
istringstream data(line);
while(data >> num){
do stuff...
}
所以从昨天开始我就一直在纠结这个问题,我检查了这里的多篇帖子试图解决这个问题,基本上,我试图从标准输入中读取 1 行或更多行到字符串变量,然后使用 istringstream 获取整数值。这就是我所拥有的:
string line;
int num;
while(getline(cin, line)){
istringstream data(line);
while(data >> num){
do stuff...
}
}
然而,外层循环永远不会退出,如果标准输入中没有输入,它只是坐在那里等待,永远不会真正退出循环,所以程序基本上会暂停,直到输入内容,然后继续循环再一次。有人能告诉我为什么 getline 在 stdin 上没有任何内容时不只是导致退出条件吗?有人能帮我解决这个问题吗?您的帮助将不胜感激。
if there is no input in the standard input it just sits there waiting and never actually exits the loop, so the program basically pauses until something is entered, and then just continues the loop once more. Can someone tell me why getline doesn't just cause an exit condition when there is nothing on stdin
它的行为符合预期。 "nothing on stdin" 实际上是什么?你的意思是一个空的输入?在这种情况下,您可能希望将循环条件更改为
while(getline(cin, line) && !line.empty()){
也如评论中所述CTRL-Z或CTRL-D(取决于OS)后跟ENTER 输入可能会结束循环。
问题是标准输入 (cin) 将读取一行,并且由于 getline 返回 'true'(引用 != 0),循环将永远继续请求另一行。
如果你想从输入中读取一行,你应该避免 while:
string line;
int num;
getline(cin, line)){
istringstream data(line);
while(data >> num){
do stuff...
}