关闭while(cin.good())正确循环

时间:2016-01-26 16:36:26

标签: c++ if-statement while-loop break peek

我正在努力让程序在没有它的情况下正常退出。我有'|'作为我的退出,如果它是我第一次运行时做的第一件事,那就很好了。但输入值并打印后,再输入“|”退出。 打印出来: “较小的值为0 较大的是前一个第二个值“//想要将其从显示中移除

int main()
{    
double first = 0, second = 0;
while(cin.good()){
    char exit;
    cout << "Enter '|' to exit.\n";
    cout << "Enter two numbers:";
    cin >> first >> second;
    exit = cin.peek();

    if(exit=='|'){
        break;}
    else{
        if(first<second){
            cout << "\nThe smaller value is " << first << "\nThe larger value is " << second << endl;
        }
        else if(first>second){
            cout << "\nThe smaller value is " << second << "\nThe larger value is " << first << endl;
        }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

在您的代码中,您假设用户的输入将限制为可用作双重内容的内容。事实并非如此。您遇到的问题与语句exit = cin.peak();无关,而与cin >> first >> second;有关您可以通过在程序中输入任何非数字输入并观察其失败来测试此问题将{0}分配给first并保留second原样。

简而言之,因为将输入转换为双精度失败,您将获得first的不确定值,然后您的程序继续运行。

您可以使用以下代码作为示例。在这里,我首先将我的变量填充为字符串,然后在事后尝试转换。

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{    
string str_first, str_second;
double first = 0, second = 0;
while(cin.good()){
    cout << "Enter '|' to exit.\n";
    cout << "Enter two numbers:";
    cin >> str_first >> str_second;

    if( (str_first.compare("|") == 0) || (str_second.compare("|") == 0) ){
        cout << "\nThanks for playing\n" << endl;
    break;}
    else{
        first = strtod (str_first.c_str(), NULL);
        second = strtod (str_second.c_str(), NULL);
        if(first<second){
           cout << "\nFirst is small: The smaller value is " << first << "\nThe larger value is " << second << endl;
        }
        else if(first>second){
            cout << "\nSecond is small: The smaller value is " << second << "\nThe larger value is " << first << endl;
        }
    }
  }
}