Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting a string to an integer 1

Status
Not open for further replies.

random260

Programmer
Mar 11, 2002
116
US
I am new to c++ coming from Visual basic and I know there has GOT to be an easy way to convert a string to an integer (i.e. something like the Visual Basic "VAL" command
(x=val(string))) but I can't find it in my books or online. Here is an example of what I would like to do.

#include <iostream>
#include <string>
using namespace std;

string age = &quot;&quot;;
int age2 = 0.0;

int main()
{
cout << &quot;Enter your age &quot;;
getline (cin,age);

convert the info in string age to the integer age2 here

cout << age2;

return 0;
}

Yes I know I could use cin or put it directly into the int age2 - this is just a sample - what I actually have is a program that is reading several strings from disk and then one integer - I would like to input them all into a string, then just convert the one that is a number to an int. HELP!!!!!!!
Thanks
 
#include <iostream>
#include <string>

int main()
{
std::string sAge;
int iAge=0;

std::cout << &quot;Enter your age: &quot;;
std::getline( std::cin,sAge );

iAge=atoi( sAge.c_str() );

std::cout << iAge <<
std::endl;

return 0;
}
Mike L.G.
mlg400@blazemail.com
 
Thank you, worked like a charm. If you have a moment to clarify, I have yet to encounter the .c_str() - is this telling C that the sAge is a string type variable? If not, what exaclty is it doing?
Once again, thanks much

Steve
 
The c_str() method call basically returns a pointer to a C style (NULL terminated) version of the string object. Since the function atoi() has been around since the early days of C, it only accepts C style strings as arguments. Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top