Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isdigit is not working correctly

I am trying to test if a string contains an integer by iterating through the entire string and outputting the integer. My method involves converting the string to c-string , atoi the c-string and then testing if its an integer using isdigit function. For some unknown reason, isdigit function is returning false though it encounters a integer.

I need help resolving this issue

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

int main()
{
    string p = "[ab, e2cd]";

    for (int k = 0; k < p.length(); k++)
    {
        if (isdigit(atoi(p.substr(k,1).c_str())) == true) //testing done here
        {
            cout << atoi(p.substr(k, 1).c_str());
        }
    }
}
like image 658
Computernerd Avatar asked Oct 19 '25 02:10

Computernerd


1 Answers

isdigit takes an int with the value of a single character in your locale. It is OK to pass it an unsigned char cast from a char, and let the conversion to int do its thing. Since string contains chars, you can use it's elements like this:

if ( static_cast<unsigned char>(isdigit(p[k])) ) { ....
like image 57
juanchopanza Avatar answered Oct 21 '25 16:10

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!