开发者

convert string to integer in c++

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开发者_开发技巧:

For example 256 is OK but 256a is not.

Could it be done without checking the string?

Thanks


The simplest way that makes error checking optional that I can think of is this:

char *endptr;
int x = strtol(str, &endptr, 0);
int error = (*endptr != '\0');


In C++ way, use stringstream:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    stringstream sstr;
    int a = -1;

    sstr << 256 << 'a';
    sstr >> a;

    if (sstr.failbit)
    {
        cout << "Either no character was extracted, or the character can't represent a proper value." << endl;
    }
    if (sstr.badbit)
    {
        cout << "Error on stream.\n";
    }

    cout << "Extracted number " << a << endl;

    return 0;
}


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

#include <iostream>
#include <sstream>
#include <string>
#include <cmath>

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;
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜