2

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

2 回答 2

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

于 2013-09-26T02:26:38.233 回答
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>>可用的类型,并在用户插入无效数据时自动重试(清理输入缓冲区)。它还会在询问数据之前打印给定的提示,并在数据无效的情况下打印错误消息。

于 2013-09-26T02:38:30.633 回答