Convert string to integer in C ++

Hi. I know that they asked me many times, but I did not find the answer to my specific question.

I want to convert only a string containing only decimal numbers:

For example, 256 is fine, but 256a is not.

Can this be done without checking the string?

thanks

+7
c ++ string integer
source share
3 answers

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

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

In C ++ mode 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; } 
+7
source share

Another way to use C ++ style: we check the number of digits to see 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 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; } } 
+6
source share

All Articles