【问题标题】:Assignment Within the Check of a While LoopWhile 循环检查内的赋值
【发布时间】:2013-05-19 05:20:50
【问题描述】:

我正在使用 while 循环尝试以下基本求和程序:

#include <iostream>
using std::cin;
using std::cout;


int main(){

int userIn;
int runningSum =0;

while((std::cin >> userIn) != 0){
   if(userIn == 0) std::cout << "Should never execute";
   runningSum += userIn;
}
return runningSum;
}

我无法理解为什么即使用户输入 0 也会执行 while 循环。

【问题讨论】:

  • 阅读函数/运算符的参考是学习 C++ 的更好方法,而不是胡乱猜测。

标签: c++ while-loop io


【解决方案1】:

如果输入成功,(std::cin &gt;&gt; userIn) 将是 != 0,而不是如果输入是 0

要同时检查两者,您可以使用while ( (std::cint &gt;&gt; userIn) &amp;&amp; userIn )。这将首先确保输入成功,然后确保数字实际上非零。

【讨论】:

    【解决方案2】:

    习惯于参考诸如 http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

    它描述了operator>>()函数的返回值,也就是istream(cin)对象本身。这意味着

    while((std::cin &gt;&gt; userIn) != 0)

    不会做你期望它做的事情,而且循环实际上永远不会被打破。

    你真正在寻找的是类似于

    的东西
    std::cin >> userIn;
    do {
       if(userIn == 0) std::cout << "Should never execute";
       runningSum += userIn;
       std::cin >> userIn;
    } while (userIn != -1);
    

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2021-10-22
      • 2011-07-12
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多