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?

Recommended Answers

All 2 Replies

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.