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. // A program to demonstrate the use of stringstream #include <iostream> #include <sstream> 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; }
— — — — — — — — — —
#include<stdio.h> int main() { const char *str = "12345"; int x; sscanf(str, "%d", &x); printf("\nThe value of x : %d", x); return 0; }
— — — — — — — — — —
// C++ program to demonstrate working of stoi() // Work only if compiler supports C++11 or above. #include <iostream> #include <string> 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; }
— — — — — — — — — — —
// For C++11 above #include <iostream> #include <cstdlib> using namespace std; int main() { const char *str1 = "42"; const char *str2 = "3.14159"; const char *str3 = "31337 geek"; int num1 = atoi(str1); int num2 = atoi(str2); int num3 = atoi(str3); cout << "atoi(\"" << str1 << "\") is " << num1 << '\n'; cout << "atoi(\"" << str2 << "\") is " << num2 << '\n'; cout << "atoi(\"" << str3 << "\") is " << num3 << '\n'; return 0; }
No comments:
Post a Comment