C++ 检查用户输入是否是数字,而不是字符或符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19018294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ to check if user input is a number, not a character or a symbol
提问by Dewayne Phillips
I have been trying to incorporate a check to see if the input from the user is a valid input. For example my program wants the user to guess a number between 1-1000. My program works perfectly, except when the user inputs any other character other than a number it goes CRAZY. Anyways, I want it to check and make sure that the user is inputting numbers, not something silly. So I have been going in circles trying to figure this part out. I am sure it is a easy fix, but I am new to programming and this has got me stumped. Any help would be appreciated.
我一直在尝试合并检查以查看用户的输入是否有效。例如,我的程序希望用户猜测 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;
}
回答by nhgrif
Here's a snippet I like to keep around for using in these sorts of situations.
这是我喜欢保留的片段,用于在这些情况下使用。
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;
}
Then any place you want to use cin>>guess
, instead, use guess = validInput();
然后你想使用的任何地方cin>>guess
,而是使用guess = validInput();
回答by Matteo Italia
Since spreading around code similar to what @nhgrifsuggests for every acquisition is tedious and error-prone, I usually keep around the following header:
由于散布类似于@nhgrif为每次获取建议的代码是乏味且容易出错的,因此我通常保留以下标题:
#ifndef ACQUIREINPUT_HPP_INCLUDED
#define ACQUIREINPUT_HPP_INCLUDED
#include <iostream>
#include <limits>
#include <string>
template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result)
{
do
{
Os<<Prompt.c_str();
if(Is.fail())
{
Is.clear();
Is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Is>>Result;
if(Is.fail())
Os<<FailString.c_str();
} while(Is.fail());
}
template<typename InType> InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString)
{
InType temp;
AcquireInput(Os,Is,Prompt,FailString,temp);
return temp;
}
#endif
Usage example:
用法示例:
//1st overload
int AnInteger;
AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger);
//2nd overload (more convenient, in this case)
int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n");
The AcquireInput
function allows to read any type for which there's an operator>>
available and automatically retries (cleaning up the input buffer) if the user inserts invalid data. It also prints the given prompt before asking the data and the error message in case of invalid data.
该AcquireInput
函数允许读取任何operator>>
可用的类型,并在用户插入无效数据时自动重试(清理输入缓冲区)。它还在询问数据之前打印给定的提示以及在无效数据的情况下的错误消息。