gpt4 book ai didi

C++检查用户输入是否为数字,而不是字符或符号

转载 作者:太空狗 更新时间:2023-10-29 23:36:13 25 4
gpt4 key购买 nike

我一直在尝试合并检查以查看用户的输入是否有效。例如,我的程序希望用户猜测 1-1000 之间的数字。我的程序运行完美,除了当用户输入数字以外的任何其他字符时它会变得疯狂。无论如何,我希望它检查并确保用户输入的是数字,而不是一些愚蠢的东西。所以我一直在兜圈子试图弄清楚这部分。我确信这是一个简单的修复,但我是编程新手,这让我很困惑。任何帮助将不胜感激。

#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

int main()
{

bool isGuessed=true;
while(isGuessed)
{
srand(time(0));
int number=rand()%1000+1;
int guess;
char answer;


cout<<"Midterm Exercise 6\n";
cout<<"I have a number between 1 and 1000.\n";
cout<<"Can you guess my number?\n";
cout<<"Please type your first guess:\n\n";
cin>>guess;


while(guess!=number)
{



if(guess>number)
{
cout<<"\nToo high. Try again!\n\n";
cin>>guess;
}

if(guess<number)
{
cout<<"\nToo low. Try again!\n\n";
cin>>guess;
}
}
if(guess==number)
{
cout<<"\nExcellent! You have guess the number!\n";
}
cout<<"Would you like to play again (y or n)?\n\n";
cin>>answer;
cout<<"\n";

if(answer!='y')
{
isGuessed=false;
cout<<"Thanks for playing!\n\n";
system ("PAUSE");
return 0;
}

}


return 0;
}

最佳答案

这是我喜欢保留的一个片段,以便在这些情况下使用。

int validInput()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std:numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
return x;
}

然后任何你想使用cin>>guess的地方,使用guess = validInput();

关于C++检查用户输入是否为数字,而不是字符或符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018294/

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