std :: cin在读取EOF并清除[closed]后不再读取了

问题描述 投票:0回答:1
我正在从std::cin中读取带有while循环的行,该循环在引入EOF后结束。退出循环后,我调用std::cin.clear()将流放回正常状态并再次读取,但它没有进入第二个循环。

我已经检查了eofbit,并将其设置为falsefailbit也被设置为falsegoodbit被设置为true。清除后的gcout0。这是我正在运行的代码:

while (getline(std::cin, person)) { // Do stuff until I enter ^D } std::cin.clear(); // Adding std::cin >> person here doesn't work either while (getline(std::cin, person)) { // It never enters this loop }

我在做什么错?
c++ buffer cin eof istream
1个回答
1
投票

std :: cin.clear()命令清除cin中的错误标志,以便进一步的I / O操作将正确运行。 clear方法不会将cin重置为初始值。 std :: cin是流,因此您只能读取一次。

在这种情况下,我的建议是将读取的行存储在一个字符串或字符串数​​组中,或者以您喜欢的方式存储,然后从存储的数据中读取它。
© www.soinside.com 2019 - 2024. All rights reserved.