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());
}
}
}
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])) ) { ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With