isdigit raises a debug assertion when entering £ a

2020-02-15 04:52发布

The below code works for every character I type in except for £ or ¬.

Why do I get a "debug assertion fail"?

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

int main() {
    string input;
    while (1) {
        cout << "Input number: ";
        getline(cin, input);
        if (!isdigit(input[0]))
            cout << "not a digit\n";
    }
}

2条回答
2楼-- · 2020-02-15 05:17

The Microsoft docs say:

The behavior of isdigit and _isdigit_l is undefined if c is not EOF or in the range 0 through 0xFF, inclusive. When a debug CRT library is used and c is not one of these values, the functions raise an assertion.

(I'm guessing Microsoft because of the comment about an "error window", but docs for other implementations place the same limit on argument values.)

EDIT: as Deduplicator observed, the error probably arises from default char being signed on this platform, so that you are passing negative values (different from EOF). std::string uses char, not wide characters, so my original conclusion cannot be correct.

查看更多
甜甜的少女心
3楼-- · 2020-02-15 05:37

The microsoft docs say:

The C++ compiler treats variables of type char, signed char, and unsigned char as having different types. Variables of type char are promoted to int as if they are type signed char by default, unless the /J compilation option is used. In this case they are treated as type unsigned char and are promoted to int without sign extension.

And they also say:

The behavior of isdigit and _isdigit_l is undefined if c is not EOF or in the range 0 through 0xFF, inclusive. When a debug CRT library is used and c is not one of these values, the functions raise an assertion.

So char is per default signed, which means as those two characters are not ASCII they are negative in your ANSI charset, and thus you get the assertion.

查看更多
登录 后发表回答