C++ (cin.good())正确循环时关闭

C++ (cin.good())正确循环时关闭,c++,if-statement,while-loop,break,peek,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 <&

我正试图让程序在没有它的情况下正常退出。我的出口是“|”,如果这是我第一次跑步时做的第一件事,它会很好地关闭。但在输入值并打印后,输入“|”退出。 它打印出: “较小的值为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;
        }
    }
  }
}
intmain()
{    
第一双=0,第二双=0;
while(cin.good()){
字符出口;
cout first>>second;
exit=cin.peek();
如果(退出=='|'){
中断;}
否则{

如果(首先在代码中,您假设用户的输入将被限制为可用的双精度输入。情况并非如此。您遇到的问题与语句
exit=cin.peak()无关;
但对于
cin>>第一个>>第二个;
您可以通过在程序中输入任何非数字输入,并通过将0分配给
第一个
并保持
第二个
不变来观察它失败来测试这一点

简而言之,由于将输入转换为双精度的操作失败,因此首先会为
获取一个不确定的值,然后程序继续运行

您可以使用以下代码作为示例。在本文中,我首先将变量填充为字符串,然后尝试在事实发生后进行转换

#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;
        }
    }
  }
}
#包括
#包括
#包括
使用名称空间std;
int main()
{    
字符串str_第一,str_第二;
第一双=0,第二双=0;
while(cin.good()){
第一步走>>第二步走;
if((str_first.compare(“|”)=0)|(str_second.compare(“|”)==0)){

用你正在使用的语言来标记这一点是明智的。哎呀,重点是,忘了这一点。很好。当你有权限这样做时,请接受我的正确答案。