0

I was recently creating a program and trying to convert a string to an int (similarly to Integer.parseInt(x) in java) and wasn't sure if there was a c++ equivalent that i could use?

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by mike_2000_17
0

one way to convert an int is to use the a string streams. Another way is to use the function atoi().

#include <sstream> // for stringstream
#include <iostream>
#include <string>
#include <cstdlib> // for atoi()

using namespace std;

int main()
{
    int a, b;
    string number = "12345";
    stringstream ss;
    ss << number;  // input number into the string stream
    ss >> a;  // out the contents of the stream into the int
    cout << "a is: " << a << "\n";
    b = atoi(number.cd_str());  // pass a cont char * version of the string to atoi()
    cout << "b is: " << b;
    cin.get();
    return 0;
}

Edited by NathanOliver: n/a

0

The standard way to do lexical casts is to use the std::stringstream class. Here is an example:

int ToInt(const std::string& s) {
  int result;
  std::stringstream(s) >> result;
  return result;
};

The same will work with just about any type that can input/output with the standard IO streams in C++. See the stringstream class.

For more advanced lexical-casts, you can use the Boost.Lexical-cast library.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.