gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:32:48 28 4
gpt4 key购买 nike

我试图在没有它的情况下使程序正确退出。我有'|'作为我的退出,如果它是我第一次运行时做的第一件事,它会很好地关闭。但是在输入值并打印它们之后,输入'|'退出。它打印出来:"较小的值为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; 相关 您可以测试这通过在您的程序中输入任何非数字输入并通过将 0 分配给 first 并保持 second 不变来观察它失败。

简而言之,由于将输入转换为 double 失败,您将首先获得 的不确定值,然后您的程序继续运行。

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

#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;
}
}
}
}

关于c++ - 正确关闭 while(cin.good()) 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018972/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com