Sunday, August 2, 2009

In C++ what is the easiest way to convert a string (std::string) to type int?

Lets say I have a String number


number="100"


whats the easiest way to conver this string into an int type

In C++ what is the easiest way to convert a string (std::string) to type int?
Use the standard library functions atoi (ascii to int), atof (float), or atol (long):





#include %26lt;stdlib.h%26gt;





int x = atoi("100");


float y = atof("100.1");


long z = atol("1000000");
Reply:Use streams:


string number= "100";


int x;


istringstream i(number);


if (i %26gt;%26gt; x)


cout%26lt;%26lt;x;


else


cout%26lt;%26lt;"Input not a number";





You have to include sstream for using this code. Now if you want to convert the number to float, just declare x as float and let the operator overloading do the rest.





I have provided you the code, now search net what does istringstream do and what magic can you perform with streams.
Reply:...


string s("999");


int n = atoi(s.c_str());
Reply:define it in a variable
Reply:I believe you could also simply "cast" the variable.


Here's the syntax: static_cast%26lt;type%26gt; (object)





static_cast%26lt;int%26gt;(x);





cout %26lt;%26lt; "x as integer" %26lt;%26lt; x %26lt;%26lt; endl;





I'm also pretty sure that there's no special include statements.





Hope that helps!





Rob


No comments:

Post a Comment