How to determine if a string is a number with C++?

后端 未结 30 1925
遇见更好的自我
遇见更好的自我 2020-11-22 08:46

I\'ve had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am r

30条回答
  •  无人及你
    2020-11-22 09:15

    Why reinvent the wheel? The C standard library (available in C++ as well) has a function that does exactly this:

    char* p;
    long converted = strtol(s, &p, 10);
    if (*p) {
        // conversion failed because the input wasn't a number
    }
    else {
        // use converted
    }
    

    If you want to handle fractions or scientific notation, go with strtod instead (you'll get a double result).

    If you want to allow hexadecimal and octal constants in C/C++ style ("0xABC"), then make the last parameter 0 instead.

    Your function then can be written as

    bool isParam(string line)
    {
        char* p;
        strtol(line.c_str(), &p, 10);
        return *p == 0;
    }
    

提交回复
热议问题