gpt4 book ai didi

c++ - 如果输入的值不是 C++ 中的整数,如何重复语句

转载 作者:行者123 更新时间:2023-11-28 05:58:33 26 4
gpt4 key购买 nike

我是 C++ 的新手,我正在使用 Code::Blocks 来运行我的代码...问题是,我希望用户为年龄输入一个整数值,那么我如何编写代码以确保程序知道它是否为整数,如果不是整数则循环?这是代码 [][1]

 #include <iostream>
#include <iomanip>

using namespace std;

int main()
{
int age;
string name;

cout << "Welcome To Maverick Academy! \nWe Are Pleased To Have New Student Around The Globe. \n" << endl;
cout << "What Is Your Name, Newcomer?\n";
cin >> name;
cout << "\nHello, " << name << ". How Old Are You?\n";
cin >> age;
do
{
cout << "Please Enter Your Age In Numeric. \n";
} while (cin.fail);

{
cin.clear();
}

cout << "\nPlease Choose A Class." << endl;

//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << "Classes" << setw(1) << "|" << setw(15) << left << "Advanced" << setw(1) << "|" << setw(5) << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << "Mage" << setw(1) << "|" << setw(15) << left << "Sorceress" << setw(1) << "|" << setw(5) << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record`enter code here`
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << "Fighter" << setw(1) << "|" << setw(15) << left << "Warrior" << setw(1) << "|" << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << "Ninja" << setw(1) << "|" << setw(15) << left << "Assassin" << setw(1) << "|" << setw(5) << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;

return 0;

}

最佳答案

我很确定问题出在您的 do while 循环中。

int age;
do {
if(cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Please Enter Your Age In Numeric. \n";
cin >> age;
} while(cin.fail());

应该可以。它至少运行一次循环 (do) 并不断重复(清除 cin 并提示用户输入),直到 cin.fail() 为假,此时您知道输入有效。

只是为了澄清,如果输入无效(例如,输入不适合变量类型),cin.fail() 返回 true,因此流被破坏(这就是为什么调用 cin.clear() 很重要) ).

同样值得注意的是,您需要在 cin.fail 之后加上括号,因为它是一个方法调用。 This也许能让您更深入地了解 cin、cin.fail() 和 cin.clear() 的工作原理。

关于c++ - 如果输入的值不是 C++ 中的整数,如何重复语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711607/

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