1

我试图让程序在没有它的情况下正确退出。我有'|' 作为我的出口,如果它是我第一次运行时做的第一件事,它会很好地关闭。但是在输入值并打印它们之后,然后输入'|' 退出。它打印出:“较小的值是 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;
        }
    }
  }
}
4

1 回答 1

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;
        }
    }
  }
}
于 2016-01-26T18:26:57.657 回答