Convert.To function?

Hi. I would like to know a simple way of converting string to int and int to string and so on. In C# I just had to type Convert.ToInt16(). Super simple. Is there a function or something that can convert different variables to eachother?

I tried this "atoi" I found on tutorials, but it doesn't work;

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>
#include <iostream>

using namespace std;

int main ()
{
    int i;
    string x;
    cin >> x;
    i = atoi(x);
    cout << endl << i;
}


It gives me this error;

LINE 11: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)

But int isn't a char*, right?
x is std::string. atoi() requires a parameter of type 'const char *'. There is no implicit conversion from std::string to const char *.

atoi() is no fun anyway.

1
2
3
4
5
#include <sstream>
..
std::istringstream iss( x );
int val;
iss >> val;

Obviously, if the string x does not contain value that looks like an int, then you do have an error state that you should check for.
also there is stoi() (stod(), stold()...) function defined in <string> header which basicly atoi() for strings. You can also pass someString.c_str() to atoi() function.
Topic archived. No new replies allowed.