简体   繁体   English

为什么while循环不需要用户在c ++中输入

[英]why while loop do not need user to input in c++

I'm learning c++ and reading c++ primer plus, but I don't understand why this code need two "cin >> ch". 我正在学习c ++并阅读c ++入门指南,但是我不明白为什么这段代码需要两个“ cin >> ch”。 I know the first cin will read character that was user input.but then I delete first "cin >> ch" and run code ,the program have no error.So the fist cin is necessary? 我知道第一个cin将读取用户输入的字符。但是随后我删除了第一个“ cin >> ch”并运行代码,程序没有错误。所以第一个cin是必要的吗? why the second cin needn't user to input? 为什么第二个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 read\n";
    return 0;
}

You can evaluate your input right inside condition of while loop. 您可以在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;
}

When while condition is entered it will wait for you to enter anything first. while进入状态它会等待你先输入任何内容。 Once input is received it will check if the input is not #. 收到输入后,它将检查输入是否不是#。 If input is not # the loop is entered, input printed out, counter increased, and back to waiting for another input. 如果输入不是#,则进入循环,打印输出,计数器增加,然后返回等待其他输入。 If # is entered, condition becomes false, and loop is aborted. 如果输入#,则条件为假,循环中止。

If you remove the first cin then count will never be incremented. 如果删除第一个cin则计数将永远不会增加。 The user can enter # character before entering the loop and the program can never enter it therefore. 用户可以在进入循环之前输入#字符,因此程序永远无法输入它。

The first cin>>ch is obviously used to take input from user but you have again accepting data in while loop using the same variable name "ch" , So when you run the program it will not give u error but accept only first value that you have accept before the while loop not in while loop. 很明显,第一个cin >> ch用于接收用户的输入,但是您再次使用相同的变量名“ ch”在while循环中接受数据,因此,当您运行程序时,它不会给出u错误,而仅接受第一个值您在while循环之前接受了,而在while循环中则接受了。 In while loop you can assign new value to variable "ch" but not accept the new value again. 在while循环中,您可以将新值分配给变量“ ch”,但不能再次接受新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM