How to convert string to integer in C++
In this tutorial, let’s study various ways to convert string to integer in C++.
stringstream() in C++
It is the simplest way of converting strings to integers in C++.
string stream() contains a string object with a stream that allows reading input from the input stream.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string x = "89000";
stringstream func(x);
int y = 0;
func >> y;
cout << y;
return 0;
}
Output
Value of y : 89000
Here, we see that the 89000 will be initialized as string, but later on, applying the stringstream() function, it converts into integers.
scanf() in C++
scanf() function is in C library. In this, the input is taken from the string declared than the input stream.
#include<stdio.h>
int main()
{
const char *str = "98654";
int z;
sscanf(str, "%d", &z);
printf(" %d", z);
return 0;
}Output
89654
atoi() in C++
atoi() function is used to convert string values to integer values in C++. This function takes the string value as an argument and returns the integer value.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
const char* str1 = "-789 speedy";
const char* str2 = "89.988765";
const char* str3 = "0.876";
const char* str4 = "codespeedy";
int num1 = atoi(str1);
int num2 = atoi(str2);
int num3 = atoi(str3);
int num4 = atoi(str4);
cout << num1 << '\n';
cout << num2 << '\n';
cout << num3 << '\n';
cout << num4 << '\n';
return 0;
}
Output
-789 89 0 0
In the above example, we see the different types of strings passed in atoi() function.
when the argument is not integer values, then the atoi() function returns 0.
Leave a Reply