1

I'm creating an encryption/decryption program in C++, and I use three user-provided numbers to customize the encryption. I read about isdigit() on cplusplus.com, and made a function based on that:

bool is_numeric(char *string)
{
    int sizeOfString = sizeof(string);
    int iteration = 0;
    bool isNumeric = true;

    while(iteration < sizeOfString)
    {
        if(!isdigit(string[iteration]))
        {
            isNumeric = false;
            break;
        }

        iteration++;

    }

    return isNumeric;
}

However, it doesn't seem to work. Whether I give it a number, or a non-numeric character, it still returns false. What is wrong with my approach.

4

4 回答 4

5

我想我会使用标准算法:

bool is_numeric(char const *string)
{
    return std::all_of(string, string+strlen(string), 
                       [](unsigned char c) { return ::isdigit(c); });
}

请注意,就目前而言,您的代码可能(通常会)具有未定义的行为(如果字符串包含任何在编码为 char 时结果为负数的内容)。这段代码通过在传递给 lambda 时将其转换char为 an 来防止这种情况发生unsigned char——这就是为什么我使用 lambda 而不是仅仅::isdigit作为谓词传递给all_of.

于 2013-08-09T20:07:10.407 回答
3

你计算sizeOfString错了。试试这个。

bool is_numeric(char *string)
{
    int sizeOfString = strlen(string);
    int iteration = 0;
    bool isNumeric = true;

    while(iteration < sizeOfString)
    {
        if(!isdigit(string[iteration]))
        {
            isNumeric = false;
            break;
        }

        iteration++;

    }

    return isNumeric;
}

您可能还想添加检查.角色的功能!现在您的代码仅在您的字符串是整数时才返回 true。

于 2013-08-09T19:56:38.893 回答
1

Another possible solution is using a stringstream:

bool isNumeric(const string& s) {
    stringstream ss(s);
    int val;
    ss >> val;
    return ! ss.fail() && ss.eof();
}

stringstream::operator>>(int&) will make the stringstream's failbit to be set if the given string is not numeric, and you need to check if all that's in the string is exactly one integer (and nothing else), so you also test for the eof bit. This also works for negative numbers, and you can also change the int to double if you want to accept floating point numbers.

于 2013-08-09T20:09:59.173 回答
1
while ('0' <= *string && *string <= '9')
    ++string;
return *string == '\0';

或者,如果您更喜欢使用isdigit

while (is digit((int)*string))
    ++string;
return *string == '\0';
于 2013-08-09T20:07:47.517 回答