Converting Strings To Numbers in C - C++
Converting Strings To Numbers in C - C++
Output:
Value of x : 12345
sscanf() is a C style function similar to scanf(). It reads input from a string rather that standard input.
#include<stdio.h>
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 oat and double using %f and %lf respectively.
2. 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:
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:
Output:
atoi("42") is 42
atoi("3.14159") is 3
atoi("31337 geek") is 31337
stoi() vs atoi()
int stoi (const string& str, size_t* index = 0, int base = 10);
Similarly, for converting String to Double, atof() can be used. The above function returns the converted integral number as an int value. If
no valid conversion could be performed, it returns zero.
Exercise
Write your won atof() that takes a string (which represents an oating point value) as an argument and returns its value as double.
Reference:
http://www.cplusplus.com/reference/string/stoi/
http://www.cplusplus.com/reference/sstream/stringstream/
http://www.cplusplus.com/reference/cstdlib/atoi/