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

后端 未结 30 2372
遇见更好的自我
遇见更好的自我 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:25

    include 
    

    For Validating Doubles:

    bool validateDouble(const std::string & input) {
    int decimals = std::count(input.begin(), input.end(), '.'); // The number of decimals in the string
    int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
    
    if (input.size() == decimals + negativeSigns) // Consists of only decimals and negatives or is empty
        return false;
    else if (1 < decimals || 1 < negativeSigns) // More than 1 decimal or negative sign
        return false;
    else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
        return false;
    else if (strspn(input.c_str(), "-.0123456789") != input.size()) // The string contains a character that isn't in "-.0123456789"
        return false;
    return true;
    

    }

    For Validating Ints (With Negatives)

    bool validateInt(const std::string & input) {
    int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
    
    if (input.size() == negativeSigns) // Consists of only negatives or is empty
        return false;
    else if (1 < negativeSigns) // More than 1 negative sign
        return false;
    else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
        return false;
    else if (strspn(input.c_str(), "-0123456789") != input.size()) // The string contains a character that isn't in "-0123456789"
        return false;
    return true;
    

    }

    For Validating Unsigned Ints

    bool validateUnsignedInt(const std::string & input) {
    return (input.size() != 0 && strspn(input.c_str(), "0123456789") == input.size()); // The string is not empty and contains characters only in "0123456789"
    

    }

提交回复
热议问题