Is there a way to convert a string to an int in c++?

HJB417

Senior member
Dec 31, 2000
763
0
0
I know the string is all numbers and I want to convert it to string but VC++ won't let me cast it.
string yea ="432";
int number;
number = (int)yea;

***error C2440: 'type cast' : cannot convert from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'int'. No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called.***
 

Cat

Golden Member
Oct 10, 1999
1,059
0
0
int atoi(const char *)

is the library function you need. It takes a null terminated string as an input, so you'd have to do

string blah = "123";
int dee;

dee = atoi( blah.c_str() ) ;

to convert the string object into a C string, then to an integer.

 

Elledan

Banned
Jul 24, 2000
8,880
0
0
Just for reference, you can also use stringstreams to convert a string to just about anything (int, char etc.). It's quite convenient.
 

oLLie

Diamond Member
Jan 15, 2001
5,203
1
0
What does String.parseInt do again?

*edit* oops thinking in Java.