Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"std::isdigit" is crashing for few extended ASCII Chars

Tags:

c++

std

Due to some requirements, I need to walk through a string to see if any number exists in the string.

When I was trying below code, during my testing, the application crashed.. After careful observation, I noticed that the input string has special characters (extended ASCII Chars)..

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string wordstr("tes¶¶"); //
    //int num  = unsigned char('¶'); // ASCII 182 (DEC)
    //int num1  = unsigned char('T'); // ASCII 84 (DEC)
    std::find_if(wordstr.begin(), wordstr.end(), ::isdigit) != wordstr.end();  
    return 0;
}

Why std::isdigit is crashing for extended ASCII values? (tried with few).

Is there any alternate standard function to find if the character is numeric, which wont crash if I have special chars in my input string?

note: I am not supposed use C++11 and above, due to maintenance issues of this code base.

like image 211
Pavan Chandaka Avatar asked Jan 05 '23 05:01

Pavan Chandaka


1 Answers

The <ctype.h> classification functions nominally accept an int, but the input value must be representable as an unsigned char or be the special value EOF. All other input result in undefined behavior. C11 §7.4p1:

In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

C++ inherited this restriction. The solution is to cast any plain char argument to unsigned char (not unsigned!) before passing it to ::isdigit, or to use the C++ locale-aware overload in <locale>.

like image 78
T.C. Avatar answered Jan 17 '23 19:01

T.C.