2

好的,我正在尝试熟练使用指针,因此我正在尝试为用户输入编写输入验证,以确保正确处理任何不是数字的内容。当我使用 isdigit() 时对我不起作用。当我输入字母时,我仍然会遇到异常。有什么建议么?谢谢。看一下这个:

#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";
        }
    }
}
4

3 回答 3

4

如果您if (!(cin >> arr[count])) ...改为测试 -isdigit(arr[digit])测试 的值arr[digit]是否为数字的 ASCII 码 [或可能与日语、中文或阿拉伯语匹配(即,作为阿拉伯语脚本字体,而不是像我们的“阿拉伯语”字体那样的 0-9)数字]。所以如果你输入 48 到 57,它会说没问题,但是如果你输入 6 或 345,它会抱怨它不是数字......

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

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

于 2013-07-31T23:30:44.970 回答
1

我进行这种输入验证的方式是我std::getline(std::cin, str)用来获取整行输入,然后使用以下代码对其进行解析:

std::istringstream iss(str);
std::string word;

// Read a single "word" out of the input line.

if (! (iss >> word))
    return false;

// Following extraction of a character should fail
// because there should only be a single "word".

char ch;
if (iss >> ch)
    return false;

// Try to interpret the "word" as a number.

// Seek back to the start of stream.

iss.clear ();
iss.seekg (0);
assert (iss);

// Extract value.

long lval;
iss >> lval;

// The extraction should be successful and
// following extraction of a characters should fail.

result = !! iss && ! (iss >> ch);

// When the extraction was a success then result is true.

return result;
于 2013-08-01T09:18:51.103 回答
0

isdigit()在您尝试时适用于char不适用。intcin >> arr[count];语句已经确保在输入中给出整数数字格式。检查cin.good()!cin分别)可能的输入解析错误。

于 2013-07-31T23:33:46.387 回答