gpt4 book ai didi

c++ - 带 getline 的 while 循环不会因用户输入而结束

转载 作者:行者123 更新时间:2023-12-02 00:13:54 26 4
gpt4 key购买 nike

我以为getline停在换行符处,但是while循环没有结束?它返回正确的数据,但它只是位于终端窗口中。例如:

Enter an expression: #5+4#5+4
(blinking cursor)

(可以一直输入数据,一直按回车不会退出)

我的代码(main.cpp):

    int main()
{
string exp;
cout << "Enter an Infix Expression:";

while (getline(cin, exp, '#'))
{
string token = exp;
string post;
cout << token << endl;
IntoPost *infix = new IntoPost(token.length());
post = infix->inToPost(token);
cout << post << endl;
}
cin.get();
}

最佳答案

使用 EOF 的解决方案

您当前的程序正在无限循环,因为 getline返回 std::basic_istream ,因此 while(getline()) 永远不会等于 'false'。

正如 @0x499602D2 所说,您的程序正在按预期工作,但从 getline 中提取只能以两种方式结束,如引用文献 here 所示。 :

Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for when no delimiter is specified).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

第一个条件很难实现,因为控制台上的输入是由\n 字符触发的。

至于第二个条件,根据@DavidC.Rankin:

You can also generate a manual EOF on Linux with [Ctrl+d] or windows with [Ctrl+z] (generally twice is required)

这意味着解决方案是使用 [Ctrl+d] 或 [Ctrl+z] 随时触发第二个条件来结束 while 循环。

<小时/>

使用 Break 语句的替代方法

您可以尝试结束循环的另一种方法是在输入“退出”字符串时中断:

(1)

#include <algorithm>
//...
while (getline(cin, exp, '#'))
{
// removes meaningless endline chars from input
exp.erase(std::remove(exp.begin(), exp.end(), '\n'), exp.end());
if (exp == "exit"){
break;
}
//... Your While Block Code Here!
}

要打破 while 循环,您可以简单地使用:

exit#

# 注意,endls来自您的couts在循环中将渗入您的输入在您的下一个 while (getline(cin, exp, '#')) 上,给我们不需要的换行符。为了防止这种情况,我们可以使用 std::erase() 删除输入中的结束行。如果您希望在输入中保留这些结尾,只需设置 string token = exp;在erase()行前面。

关于c++ - 带 getline 的 while 循环不会因用户输入而结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com