Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ parse int from string [duplicate]

Tags:

c++

string

int

Possible Duplicate:
How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10"; int i = s....? 

Thanks!

like image 261
kralco626 Avatar asked Dec 14 '10 18:12

kralco626


People also ask

Can you parse a string to an int?

In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.

How do you extract an int from a string in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

Which method converts a string into an int?

ToInt32(String) method to convert an input string to an int.


1 Answers

  • In C++11, use std::stoi as:

     std::string s = "10";  int i = std::stoi(s); 

    Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

  • In C++03/98, any of the following can be used:

     std::string s = "10";  int i;   //approach one  std::istringstream(s) >> i; //i is 10 after this   //approach two  sscanf(s.c_str(), "%d", &i); //i is 10 after this 

Note that the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

int to_int(char const *s) {      if ( s == NULL || *s == '\0' )         throw std::invalid_argument("null or empty string argument");       bool negate = (s[0] == '-');      if ( *s == '+' || *s == '-' )           ++s;       if ( *s == '\0')         throw std::invalid_argument("sign character only.");       int result = 0;      while(*s)      {           if ( *s < '0' || *s > '9' )             throw std::invalid_argument("invalid input string");           result = result * 10  - (*s - '0');  //assume negative number           ++s;      }      return negate ? result : -result; //-result is positive! }  

This solution is slightly modified version of my another solution.

like image 150
Nawaz Avatar answered Sep 28 '22 20:09

Nawaz