gpt4 book ai didi

c++ - 输入错误会导致程序退出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:33 25 4
gpt4 key购买 nike

看这段代码:

#include <iostream>
using namespace std;
int main()
{
string s;
int n;
float x;
again:
cout << "Please Type this: ABC456 7.8 9 XYZ\n";
cin >> s >> n >> x >> s;
cout << "\nDo you want to try Again(y/n)? ";
char t;
cin >> t;
if (t=='y' || t=='Y')
goto again;
return 0;
}

只需尝试输入“ABC456 7.8 9 XYZ”并按回车键,它会导致程序退出,然后提示用户重试。我知道输入是错误的,它们不属于它们的类型,但为什么会导致退出?以及如何避免这种退出?

最佳答案

改变

cin >> s >> n >> x >> s;

cin >> s >> x >> n >> s;

当您输入 7.8 作为第二个输入时,您将其收集在整数变量而不是浮点变量中。因此,当您输入时:

ABC456 7.8 9 XYZ

s得到ABC456n得到7(因为是int类型,输入缓冲区还在其中有 .8 9 XYZ\n)。接下来 n 得到 .8,最后 s 得到 "9"。现在输入缓冲区中有 XYZ\n。下次当您将输入读入 t 以获得用户的选择时,X 会被读入 t 并且因为它不是 yY,循环退出。

关于c++ - 输入错误会导致程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10379274/

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