理解计算 char 变量的 C++ 问题

标签 c++ c++11

我写了一个程序,它应该打印我输入的字符数,直到它命中“#”字符。我不明白的是,当我在控制台中输入多个字符(比如“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/

相关文章:

C++ 禁止将 `string` 常量转换为 `char*` - Alphabets to Morse converting program

c++ - { Qt5.0.2/QML/QtQuick2.0/C++ } 运行没有错误的示例项目?

c++ - main() 可以有异常规范吗?

c++ - 概括这些代码行?

c++ - 字符串的最小字典序值

c++ - 我如何从 while(getline(cin,tmp)) 跳转?

c++ - 对服务器/客户端应用程序使用 Kerberos 身份验证

c++ - 在 Xcode 中静态链接 id3lib 的问题

c++ - 避免在必须增加维度时重新分配 vector

c++ - 构建 wxWidgets 应用程序失败 - 未定义对 `wxCRT_StrdupA(char const*)' 的引用