while循环中断,我不知道原因

Man*_*ngh 3 c++ codeblocks while-loop c++11

我正在为一个柜台写一个代码.如果我给'a'作为输入,它应该+1计数器并在屏幕上显示它.但是当我这样做时,它在屏幕上显示1并且程序结束.我希望它一直运行,除非我给出一些其他字符作为输入.我犯的错是什么?

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int Counter = 0;
    char t;

    while(true)
    {
        t = cin.get();
        if(t == 97)
        {
            Counter = Counter + 1;
        }
        else
            break;
        system("cls");
        cout << Counter;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 6

问题是当你进入你的时候'a',你可能Enter也会受到影响,这被解释为另一个char.第二个char肯定不是a,所以你的程序会中断.这可以通过输出您阅读的内容来验证:

for (;;) {
    std::cout << '?';
    char t = std::cin.get();
    std::cout << (int)t << '\n';
    if (t != 'a') break;
}
std::cout << "done\n";
Run Code Online (Sandbox Code Playgroud)

在运行时打印:

?a
97   // this is 'a'
?10  // this is '\n', note the additional ?
done
Run Code Online (Sandbox Code Playgroud)

最简单的解决方法是使用输入流操作符cin,这将丢弃输入中的空格(而get()不是):

char t;
for (;;) {
    std::cout << '?';
    std::cin >> t;
    std::cout << (int)t << '\n';
    if (t != 'a') break;
}
std::cout << "done\n";
Run Code Online (Sandbox Code Playgroud)

哪个在运行时产生:

?a
97 
?b
98 
done
Run Code Online (Sandbox Code Playgroud)

这是你的意图.