int number = std::stoi(string, base);// str to intint number = std::stoi("100",10);// number = 100longint number = std::strtol(string, endptr, base);// str to long int
#include<iostream>#include<string>usingnamespace std;intmain(){// a string variable named str
string str ="7";//print to the console
cout <<"I am a string "<< str << endl;//convert the string str variable to have an int value//place the new value in a new variable that holds int values, named numint num =stoi(str);//print to the console
cout <<"I am an int "<< num << endl;}
//stoi() : The stoi() function takes a string as an argument and //returns its value. Supports C++11 or above. // If number > 10^9 , use stoll().#include<iostream>#include<string>usingnamespace std;main(){
string str ="12345678";
cout <<stoi(str);}
// For C++11 and later versions
string str1 ="45";
string str2 ="3.14159";
string str3 ="31337 geek";int myint1 =stoi(str1);int myint2 =stoi(str2);int myint3 =stoi(str3);// Outputstoi("45") is 45stoi("3.14159") is 3stoi("31337 geek") is 31337
// C++ program to demonstrate working of stoi()// Work only if compiler supports C++11 or above// Because STOI() was added in C++ after 2011#include<iostream>#include<string>usingnamespace std;intmain(){
string str1 ="45";
string str2 ="3.14159";
string str3 ="31337 geek";int myint1 =stoi(str1);// type of explicit type castingint myint2 =stoi(str2);// type of explicit type castingint myint3 =stoi(str3);// type of explicit type casting
cout <<"stoi("" << str1 << "") is "<< myint1
<< '
';
cout <<"stoi("" << str2 << "") is "<< myint2
<< '
';
cout <<"stoi("" << str3 << "") is "<< myint3
<< '
';return0;}
string str1 ="45";
string str2 ="3.14159";
string str3 ="31337 geek";int myint1 =stoi(str1);// type of explicit type castingint myint2 =stoi(str2);// type of explicit type castingint myint3 =stoi(str3);// type of explicit type casting/* Result
45
3
31337
*/
#include<iostream>#include<string>// namespace because why notnamespace dstd
{intStringtoInt(std::string str){int multiplier =1;int sum =0;for(int i = str.size()-1;i >=0; i--){switch(str[i]){case'0':
sum +=0;break;case'1':
sum +=1* multiplier;break;case'2':
sum +=2* multiplier;break;case'3':
sum +=3* multiplier;break;case'4':
sum +=4* multiplier;break;case'5':
sum +=5* multiplier;break;case'6':
sum +=6* multiplier;break;case'7':
sum +=7* multiplier;break;case'8':
sum +=8* multiplier;break;case'9':
sum +=9* multiplier;break;case'-':
sum *=-1;break;case' ':continue;case}
multiplier *=10;}return sum;}}intmain(){//just an example of how to use the functionint a = dstd::StringtoInt("1992");
std::cout<<a<<'
';}