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

时间:2013-09-26 02:22:06

标签: c++

我一直在尝试合并检查以查看用户的输入是否是有效输入。 例如,我的程序希望用户猜测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;
}

2 个答案:

答案 0 :(得分:8)

这是我喜欢在这些情况下使用的片段。

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();

答案 1 :(得分:3)

由于传播代码类似于 @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

用法示例:

//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");

AcquireInput函数允许读取任何可用operator>>的类型,并在用户插入无效数据时自动重试(清理输入缓冲区)。它还在询问数据之前打印给定的提示,并在数据无效的情况下打印错误消息。