为什么 while 循环不需要用户在 C++ 中输入
why while loop do not need user to input in c++
我正在学习 c++ 并阅读 c++ 入门 plus,但我不明白为什么这段代码需要两个"cin>> ch"。我知道第一个 cin 会读取用户输入的字符,但随后我删除了第一个"cin>> ch"并运行代码,程序没有错误。所以拳头是必要的吗?为什么第二个CIN不需要用户输入?
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:n";
cin >> ch; //get a character
while (ch != '#')
{
cout << ch;
++count;
cin >> ch; // get the next character
}
cout << endl << count << " characters readn";
return 0;
}
您可以在循环while
条件内评估输入。
#include <iostream>
int main()
{
char ch;
int count = 0;
std::cout << "Enter characters; enter # to quit:n";
while (std::cin >> ch && ch != '#')
{
std::cout << "entered: " << ch << std::endl;
++count;
}
std::cout << std::endl << count << " characters read" << std::endl;
return 0;
}
输入条件while
它将等待您先输入任何内容。收到输入后,它将检查输入是否不是#。如果输入不是#,则进入循环,输入打印出来,计数器增加,然后返回等待另一个输入。如果输入 #,条件变为 false,循环中止。
如果删除第一个cin
则计数将永远不会增加。用户可以在进入循环之前输入#
字符,因此程序永远无法输入它。
第一个 cin>>ch 显然用于从用户那里获取输入,但您再次使用相同的变量名"ch"在while循环中接受数据,因此,当您运行程序时,它不会给出 u 错误,而是只接受您在 while 循环而不是 while 循环之前接受的第一个值。 在 while 循环中,您可以将新值分配给变量 "ch",但不能再次接受新值。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type