-4

How can I convert a string to an Integer in C++?

I tried the following code:

string num1="102";
string num2="110";
int n1,n2;
stringstream ss2(num1);
ss2>>n1;
stringstream ss3(num2);
ss3>>n2;

I am getting the same garbage value for n1 and n2 but I am not getting the Integer values.

Are the steps that I wrote were correct or wrong? If they are correct, why am I not getting correct answer? If they are not correct, what is the correct way of converting string to integer?

Please do reply... Thanks in advance

Sakthi Kumar
  • 3,047
  • 15
  • 28
VAMSHI PAIDIMARRI
  • 236
  • 1
  • 4
  • 9

3 Answers3

4

The easiest way to convert an std::string to an int is:

std::stoi(yourString);

to convert from std::string to long or long long you can use:

std::stol(yourString);  //long
std::stoll(yourString); //long long

Documentation

This solution will work only with C++11 code. Consider using an istringstream instead of a stringstream in your current code if you do not have access to C++11.

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
1
atoi( num1.c_str() )

, where num1 is your string, is one of the best solutions.

Andrea
  • 6,032
  • 2
  • 28
  • 55
1

IF YOU ARE USING C++11, YOU CAN USE THE FOLLOWING:

It appears this snippet of code is okay: can you please post a large block of code or the entire file so that we may inspect it? The answer may not always be where you are looking for it.

On another note, why not use boost::lexical_cast? If you're not feeling up to it, I have a copy of a non-boost lexical_cast function here that works just as it is:

#include <iostream>
#include <string>
#include <sstream>
#include <typeinfo>

template <typename T>
T lexical_cast(const std::string& s)
{
    std::stringstream ss(s);

    T result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof())
    {
        throw std::bad_cast();
    }

    return result;
}

Notice how this form of the function uses std::stringstream as well, so why just use it alone? The good thing about this is that it is usable for more than just int, as, being a template, it can also accommodate other types of data. Note that I only tested this with int and float.

Note: if you decide to use this *template version of lexical_cast* and put it in a separate file, you will end up having to declare it within the header file.

To call lexical_cast with an int:

int whatever = lexical_cast <int>(stringOfYourChoice);
CinchBlue
  • 6,046
  • 1
  • 27
  • 58