For the C, we had the famous atoi() function, but for C++, how can I convert a std::string into an int?
#include <sstream> #include <string> #include <iostream> int main (void) { std::string myString = "100"; int result; std::stringstream convertThis(myString); if (!(convertThis >> result)) result = 0; result += 5; std::cout << "Result = " << result << std::endl; }
$ Result = 105
#include <sstream> #include <string> #include <iostream> int main (void) { int myNumber = 250; std::string myString; std::stringstream convertThis; convertThis << myNumber; myString = convertThis.str(); std::string newString = "I saw "; newString += myString; newString += " birds in the sky!"; std::cout << newString << std::endl; }
$ I saw 250 birds in the sky!
Add new comment