【问题标题】:Unable to get desired result in C++无法在 C++ 中获得所需的结果
【发布时间】:2015-05-24 17:24:01
【问题描述】:

我正在使用这段代码做某事 -

// Initialize variables
double x;
...
// Here is where I'm facing problem
while (cin >> x){
    if (x == '|'){
        cout << "\nBreaking the loop\n"; // Edit1: Unable to produce output
        break;
    }
   // Do something
     ...
}

// Do some other things
cout << "\nAfter the loop";       // Edit1: This gets executed,
cin >> x;                         //        but this doesn't.
...
// End

但是,当我输入 '|' 时,窗口关闭,甚至没有输出这个 - Breaking the loop 并且不执行 while 循环之后的语句(我认为)。

我正在使用 Visual C++。

为什么会这样?有什么解决办法吗?

【问题讨论】:

  • 它破坏了外观,因为 cin >> x 评估为 false 为 '|'不能初始化为双精度。
  • | 不是 double 值的文本表示中的有效字符。因此,cin &gt;&gt; x 在输入流中遇到此字符时会设置cin.failbit()。这会导致循环条件变为false
  • 试试cout &lt;&lt; "\nBreaking the loop" &lt;&lt; endl;
  • @IvanWalulya:但是即使我使用int,而不是double,它也会产生输出Breaking the loop,但窗口仍然会再次关闭,并且在一段时间之后它不会执行任何代码循环。
  • 一旦failbit 在流上设置,它将保持设置状态。您可以使用cin.clear() 重置它。此外,| 字符从未从输入流中提取 - 如果您尝试再次读取double,则读取的第一个字符将是|,它会再次以与第一次相同的方式失败。您可以使用cin.ignore() 跳过某些字符。

标签: c++ visual-c++


【解决方案1】:

改为使用 char 而不是 double

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
 {
 char x;
 // Here is where I'm facing problem
 while (cin >> x){
    if (x == '|'){
        cout << "\nBreaking the loop\n";
        break;
    }
   // Do something
 }

 }

【讨论】:

  • 但对于其他情况,我总是必须将x 视为double。这是一段代码仅用于退出循环。
  • 如果你需要一个字符退出序列,那么你将不得不使用一个 cin >> 字符串,然后使用 atof 转换为双精度。但显然隐式转换并没有发生。
  • 是的,我同意你的看法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多