Use of stoi in C++
In this tutorial, we shall have a look at the use of stoi in C++.
stoi() in C++
stoi() is a function that takes a string as input and returns the integer values.
First Example of stoi function
#include <iostream> #include <string> using namespace std; int main() { string a = "500"; int x = stoi(a); cout << x << endl; }
Output
500
Initially, 500 is declared in a string, upon using the stoi function, it is converted into an integer.
Example 2
#include <iostream> #include <string> using namespace std; int main() { string a = "10000 codespeedy"; int x = stoi(a); cout << x << endl; }
Output
1000
Here 1000 codespeedy is declared as a string, later upon using the stoi function, it returns the integer values.
Example 3
#include <iostream> #include <string> using namespace std; int main() { string a = "8941.0987421"; int x = stoi(a); cout << x << endl; }
Output
8941
in this example, we see that float value is declared as a string, by using stoi() function, it returns the integer values.
You can also read: C++ Pre-Processors
Leave a Reply