views:

167

answers:

4

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

+10  A: 

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');
Evan Teran
+2  A: 

a integer cannot be 256a.. There are lots of functions doing this. You coul use std::stringstream,too

EDIT:or you really mean string to int..?

Kiril Kirov
yes thats what i meant
Yakov
i would suggest the same as Evan. But if you want to cut the first n digits from a string,you could use stringstream,for example 2562asd1t will be 'parsed' as 2562: Also,you could check the documentation for stringstream and see which flag is raised,if not the whole string was accepted(http://cplusplus.com for ex.)
Kiril Kirov
+5  A: 

In C++ way, use stringstream:

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

int main()
{   
    stringstream sstr;  
    int a;

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

    cout << a << endl; // outputs 256 on VS 2008

    return 0;
}
Donotalo
+2  A: 

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

}
Elenaher