简体   繁体   English

使用cin在while循环中进行条件

[英]Condition in while loop using cin

I have following code 我有以下代码

 //in main
 int x;
 while ( cin>>x ){
        // code goes here
 }

Now,i know that this loop executes untill read to x fails which occurs when type mismatch occurs 现在,我知道此循环将执行到读取x失败为止(发生类型不匹配时发生)
So pressing a char lets me to come out of loop as x is of type int and char will not be read from input stream. 因此,按char可以使我走出循环,因为x的类型为int并且不会从输入流中读取char
But problem is with whitespaces, as they are also not int so why loop does not ends when i press enter or whitespace? 但是问题出在空格上,因为它们也不是int ,为什么当我按Enter或空格时循环没有结束?

According to The C++ Programming Language Special Edition , $21.9 Advice [5]: 根据C ++编程语言特别版 ,价格为$ 21.9,建议[5]:

Remember that by default >> skips whitespace; 请记住,默认情况下>>会跳过空格; §21.3.2. 第21.3.2条。

And in $21.3.2: 而在$ 21.3.2中:

Whitespace is defined as the standard C whitespace (blank, tab, newline, formfeed, and carriage return) by a call to isspace() as defined in (§20.4.2). 空格通过调用(§20.4.2)中定义的isspace()定义为标准C空格(空白,制表符,换行符,换页符和回车符)。

The comment of @jrok provided the answer. @jrok的评论提供了答案。

Hence, as long as the input is a white space cin waits for input which may represent the requested type. 因此,只要输入是空白,cin就等待可能代表所请求类型的输入。 It stops if an invalid character is in the stream or - after a valid non white space character has been consumed - the character is a white space. 如果流中包含无效字符,或者在消耗了有效的非空白字符后,该字符为空白,它将停止。

You might read line by line to detect empty input: 您可能会逐行阅读以检测空输入:

std::string line
while(getline(cin, line)) {
    // Note: Omitting the case where the line contains spaces, only.
    if(line.empty()) {
       // No input;
       break;
    }
    else {
       // Parse and process the line.
    }
}

Note: If skipping white spaces is disabled, the behavior changes. 注意:如果禁用了跳过空格,则行为会更改。

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

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