Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 967
Yakov Avatar asked Oct 04 '10 20:10

Yakov


2 Answers

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');
like image 152
Evan Teran Avatar answered Sep 23 '22 20:09

Evan Teran


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;
}
like image 32
Donotalo Avatar answered Sep 25 '22 20:09

Donotalo