我正在尝试设置一个要求Age的基本程序,如果用户输入的数字小于99,它会说"Perfect".如果数字超过99,它会说"你不能那么老,再试一次".另外,如果用户输入的不是数字(如字母"m,r"或其他任何类似"icehfjc"),那么它会说"那不是数字".
到目前为止这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age;
backtoage:
cout << "How old are you?\n";
cin >> age;
if (age < 99)
{
cout << "Perfect!\n";
system("pause");
}
if (age > 99)
{
cout << "You can't be that old, Try again.\n";
system("pause");
system("cls");
goto backtoage;
}
Else
{
cout << "That is not a number, Please Enter a Valid Number\n";
system("pause");
system("cls");
goto backtoage;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道"Else"不起作用,因为C++也将字母视为整数,所以如果我写"m"它会将它作为> 99的数字(因为"m"的整数值)因此显示"你"不能是那个旧的"消息.但是如何解决此问题,以便在输入信件时程序显示"请输入数字"?(如果有人能修复代码并以有效的方式编写代码,我会永远感激不尽).
我们非常欢迎任何建议,提示或提示.
所以,如果我写"m",它将取一个> 99的数字(因为整数值为"m")
不,"m"不能输入int,cin这里会失败.所以你应该做的是检查状态cin,例如
if (cin >> age) {
// ok
if (age < 99)
{
...
} else
{
...
}
}
else
{
// failed
cout << "That is not a number, Please Enter a Valid Number\n";
system("pause");
system("cls");
cin.clear(); // unset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
goto backtoage;
}
Run Code Online (Sandbox Code Playgroud)
检查std :: basic_istream :: operator >>的行为
如果提取失败(例如,如果输入了预期数字的字母),则值保持不变,并设置failbit.
BTW:goto在现代c ++编程中几乎已经过时了.使用循环实现相同的逻辑应该很容易.
您可以尝试它.它将在C++中验证数字输入.如果输入有效
cin.good()则返回函数true,如果输入无效则返回fase.cin.ignore()用于忽略输入缓冲区的其余部分,其中包含错误输入并cin.clear()用于清除标志.
#include <iostream>
#include<string>
#include <limits>
using namespace std;
int main() {
backtoage:
int age = 0;
cout << "How old are you?\n";
cin >> age;
if(cin.good()){
if (age < 99){
cout << "Perfect!\n";
system("pause");
}
else if (age > 99){
cout << "You can't be that old, Try again.\n";
system("pause");
system("cls");
goto backtoage;
}
}
else{
cout << "That is not a number, Please Enter a Valid Number\n";
system("pause");
system("cls");
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
goto backtoage;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入输出:
How old are you?
k
That is not a number, Please Enter a Valid Number
How old are you?
120
You can't be that old, Try again.
How old are you?
10
Perfect!
Run Code Online (Sandbox Code Playgroud)