convert string to integer in c++

前端 未结 3 613
故里飘歌
故里飘歌 2020-12-03 22:57

Hello I know it was asked many times but I hadn\'t found answer to my specific question.

I want to convert only string that contains only decimal numbers:

Fo

3条回答
  •  星月不相逢
    2020-12-03 23:25

    An other way using c++ style : We check the number of digits to know if the string was valid or not :

    #include 
    #include 
    #include 
    #include 
    
    int main(int argc,char* argv[]) {
    
        std::string a("256");
    
        std::istringstream buffer(a);
        int number;
        buffer >> number; // OK conversion is done !
        // Let's now check if the string was valid !
        // Quick way to compute number of digits
        size_t num_of_digits = (size_t)floor( log10( abs( number ) ) ) + 1;
        if (num_of_digits!=a.length()) {
            std::cout << "Not a valid string !" << std::endl;
        }
        else {
            std::cout << "Valid conversion to " << number  << std::endl;
        }
    
    }
    

提交回复
热议问题