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

closing while(cin.good()) loop properly

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

在您的代码中,您假定用户的输入将限于可用作替身的内容。不一定是这样。您 运行 遇到的问题与语句 exit = cin.peak(); 无关,但与 cin >> first >> second; 相关 您可以通过在程序中输入任何 non-numerical 输入并观察它来测试它通过将 0 分配给 first 并将 second 保持原样而失败。

简而言之,由于将输入转换为 double 失败,您会得到一个不确定的 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;
        }
    }
  }
}