我写了一个程序,它应该打印我输入的字符数,直到它命中“#”字符。我不明白的是,当我在控制台中输入多个字符(比如“hello world”)时,程序会在一次迭代中计算所有字符。为什么它在一次迭代中计算所有字符而不是 1 个?
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch);
while (ch != '#')
{
cout << ch;
++count;
cin.get(ch); // use it again
}
cout << endl << count << " characters read\n";
最佳答案
why does it count all the character in one iteration instead of 1?
事实并非如此。您可以通过在循环中稍微更改输出来验证这一点。
while (ch != '#')
{
++count;
cout << "ch: " << ch << ", count: " << count << endl;
cin.get(ch); // use it again
}
关于理解计算 char 变量的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52862026/