There are two common methods to convert strings to numbers:
Using stringstream class or sscanf()
stringstream() : This is an easy way to convert strings of digits into ints, floats or doubles. Following is a sample program using a stringstream to convert string to int.
CPP
// A program to demonstrate the use of stringstream #include #include using namespace std; int main() { string s = "12345"; // object from the class stringstream stringstream geek(s); // The object has the value 12345 and stream // it to the integer x int x = 0; geek >> x; // Now the variable x holds the value 12345 cout << "Value of x : " << x; return 0; }
Output:
Value of x : 12345 // A stringstream is similar to input/output // file stream. We need to declare a stringstream // just like an fstream, for example: stringstream ss; // and, like an fstream or cout, // we can write to it: ss << myString; or ss << myCstring; or ss << myInt;, or float, or double, etc. // and we can read from it: ss >> myChar; or ss >> myCstring; or ss >> myInt;
To summarize, stringstream is a convenient way to manipulate strings.
sscanf() is a C style function similar to scanf(). It reads input from a string rather that standard input.
CPP
#include int main() { const char *str = "12345"; int x; sscanf(str, "%d", &x); printf("\nThe value of x : %d", x); return 0; }
Output:
Value of x : 12345
Similarly we can read float and double using %f and %lf respectively.
String conversion using stoi() or atoi()
stoi() : The stoi() function takes a string as an argument and returns its value. Following is a simple implementation:
// C++ program to demonstrate working of stoi() // Work only if compiler supports C++11 or above. #include #include using namespace std; int main() { string str1 = "45"; string str2 = "3.14159"; string str3 = "31337 geek"; int myint1 = stoi(str1); int myint2 = stoi(str2); int myint3 = stoi(str3); cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n'; cout << "stoi(\"" << str2 << "\") is " << myint2 << '\n'; cout << "stoi(\"" << str3 << "\") is " << myint3 << '\n'; return 0; }
Output:
stoi("45") is 45 stoi("3.14159") is 3 stoi("31337 geek") is 31337
atoi() : The atoi() function takes a character array or string literal as an argument and returns its value. Following is a simple implementation:
C
#include #include int main() { char* str1 = "42"; char* str2 = "3.14159"; char* str3 = "31337 geek"; int myint1 = atoi(str1); int myint2 = atoi(str2); int myint3 = atoi(str3); printf("stoi(%s) is %d \n", str1, myint1); printf("stoi(%s) is %d \n", str2, myint2); printf("stoi(%s) is %d \n", str3, myint3); // This Code is Contributed by Harshit Srivastava return 0; }
Output:
atoi("42") is 42 atoi("3.14159") is 3 atoi("31337 geek") is 31337
stoi() vs atoi()
int atoi (const char * str);
int stoi (const string& str, size_t* index = 0, int base = 10);
Exercise
Write your own atof() that takes a string (which represents a floating-point value) as an argument and returns its value as double.