string to integer coversion

while working with following code error is being displayed.
//
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()

{
string s;
int a;

cin >> s;

a = atoi(s);

cout << a;

return 0;
}

//
is it because atoi takes only constant value for conversion?
if it is so,then [b]how can i convert a string(a no with any no. of digits) taken from user to integer? e.g. input string can be 3243243249840897024524692862934
[/b]
Last edited on
atoi takes a const char and you're inputing a string, just use a = atoi(s.c_str());. c_str() is a method of the string class which returns a const char.
Native integral types in C++ have a finite maximum value so the answer to your second question is that it is impossible without a bigmath library.

Having said that, using atoi does not provide you any means to check for conversion errors. Ie, atoi( "hello world" ) will probably return 0, as would atoi( "0helloworld") even though neither are integers in and of themselves. That being the case, you are no better off than simply doing

int x;
cin >> x;

At least in the latter case you can check for errors.

Topic archived. No new replies allowed.