-3

So I wrote a function that checks whether or not a string has a numeric character. Even if there is just 1 letter in a group of numbers, it should return false. However it doesn't. I'm not sure if loops work differently in C++ or not.

bool isStringAValidNumber(string str)
{
    for (int i = 0; i < str.length(); i++) {
        if (!isdigit(str[i])) {
            return false;
            break;
        }
    }
    return true;
}
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
  • Can you show the definition of isdigit? – Lajos Arpad Nov 22 '18 at 18:26
  • @LajosArpad Isn't `isdigit` defined under `std::`? It basically checks if a char is within `[0-9]`. – TrebledJ Nov 22 '18 at 18:35
  • You are going to get a reference from str[i]. Try to cast to int and check if it works. Dont need the break after false – Srikan Nov 22 '18 at 18:48
  • @Srikan "*Try to cast to int and check if it works*" - excuse me? Casting `char` to `int` will always work – Fureeish Nov 22 '18 at 22:33
  • 1
    It should be either `!isdigit( (unsigned char)str[i] )` or `!std::isdigit(str[i], std::locale())` The `is` function family are quirky due to history of being imported from the C language. Also this will not work for UTF-8 strings obviously. If you are still having trouble please post [MCVE](http://stackoverflow.com/help/mcve) that shows unexpected output. – M.M Nov 22 '18 at 23:01
  • Possible duplicate of [how to check if given c++ string or char\* contains only digits?](https://stackoverflow.com/questions/8888748/how-to-check-if-given-c-string-or-char-contains-only-digits) – Hiroki Nov 23 '18 at 13:51

1 Answers1

1
#include <iostream>
#include <string>

using namespace std;

int isStringAValidNumber(string str)
{
    for (int i = 0; i < str.length(); i++) {
        if (!isdigit(str[i])) {
            return 0;
            break;
        }
    }
    return 1;
}


int main()
{
    cout << isStringAValidNumber("1sd2345");
    cout << endl;
    cout << isStringAValidNumber("1s2345");
    cout << endl;
    cout << isStringAValidNumber("12345");
}

works just fine...

the return is:

0
0
1

Compile Online

Alireza Tbp
  • 111
  • 1
  • 7