输入验证以确保只有数字c ++ [英] Input Validation to make sure only number c++

查看:151
本文介绍了输入验证以确保只有数字c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想尽力使用指针,所以我试图写一个输入验证的用户输入,以确保任何不是一个数字被正确处理。当我使用isdigit()不是为我工作。我仍然得到一个例外,当我输入一个字母表。有什么建议么?谢谢。请查看:

 #include< iostream> 
#include< algorithm>
#include< string>
#include< cctype>
using namespace std;

void EnterNumbers(int *,int);


int main()
{
int input = 0;
int * myArray;

cout<< 请输入考试成绩的数字\\\
\\\
;
cin>>输入;

//分配数组
myArray = new int [input];

EnterNumbers(myArray,input);


delete [] myArray;
return 0;
}

void EnterNumbers(int * arr,int input)
{

for(int count = 0; count< input; count ++)
{
cout<< \\\
\\\
输入成绩编号<< count + 1< \t;
cin>> arr [count]

if(!isdigit(arr [count]))
{
cout< 不是数字;
}
}
}


解决方案>

如果你测试 if(!(cin>> arr [count]))... instead - isdigit(arr [数字])测试 arr [digit] 的值是否为数字的ASCII码[或可能匹配日语,中文或阿拉伯语是,作为一个阿拉伯文字体,不是一个0-9像我们的阿拉伯语一个数字]。所以,如果你输入48到57,它会说它的确定,但如果你键入6或345,它抱怨,它不是一个数字...



一次你发现了一个非数字,你还需要退出或清除输入缓冲区从垃圾。 cin.ignore(1000,'\\\
');
将读取到下一个换行符或1000个字符,以先到为准。如果有人输入了一百万数字,可能会烦人,但否则,应该解决问题。



您当然还需要一个循环来再次读取数字,直到输入有效的数字。


Ok, I'm trying to get good at using pointers so I'm trying to write a input validation for the user input to make sure that anything that isn't a number is handled correctly. When I use isdigit() isn't working for me. I still get an exception when I enter a alphabet. Any suggestions? Thanks. Check this out:

#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
using namespace std;

void EnterNumbers(int * , int);


int main()
{
    int input = 0;
    int *myArray;

    cout << "Please enter the number of test scores\n\n";
    cin >> input;

    //Allocate Array
    myArray = new int[input];

    EnterNumbers(myArray,input);


    delete[] myArray;
    return 0;
}

void EnterNumbers(int *arr, int input)
{

    for(int count = 0; count < input; count++)
    {
        cout << "\n\n Enter Grade Number  " << count + 1 << "\t";
        cin >> arr[count];

        if(!isdigit(arr[count]))
        {
            cout << "Not a number";
        }
    }
}

解决方案

If you test if (!(cin >> arr[count])) ... instead - isdigit(arr[digit]) tests if the value of arr[digit] is the ASCII code of a digit [or possibly matches Japanese, Chinese or Arabic (that is, as an Arabic script typeface, not that it's a 0-9 like our "Arabic" ones) digit]. So if you type in 48 to 57, it will say it's OK, but if you type 6 or 345, it's complaining that it is not a digit...

Once you have discovered a non-digit, you will also need to either exit or clean out the input buffer from "garbage". cin.ignore(1000, '\n'); will read up to the next newline or a 1000 characters, whichever happens first. Could get annoying if someone has typed in a million digits, but otherwise, should solve the problem.

You will of course also need a loop to read the number again, until a valid number is entered.

这篇关于输入验证以确保只有数字c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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