C ++来检查用户输入是否是数字,而不是字符或符号 [英] C++ to check if user input is a number, not a character or a symbol

查看:180
本文介绍了C ++来检查用户输入是否是数字,而不是字符或符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图结合一个检查,看看用户的输入是否是一个有效的输入。
例如我的程序想让用户猜测1-1000之间的数字。我的程序工作完美,除非当用户输入任何其他字符,而不是一个数字,它去CRAZY。无论如何,我想要检查,并确保用户输入数字,不是什么愚蠢。所以我一直在努力想出这个部分。我相信这是一个容易解决,但我是新的编程,这让我陷入困境。任何帮助将不胜感激。

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.

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

Then any place you want to use cin>>guess, instead, use guess = validInput();

这篇关于C ++来检查用户输入是否是数字,而不是字符或符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆