In the previous article, we have discussed about C++ Program to Convert Single Character to String. Let us learn how to Convert String to a Number in C++ Program.
Program to Convert String to a Number in c++
In this article, we discuss how we can convert a string to a number in c++. For example, suppose we a string “123” then we have to convert it to integer 123. The methods that are discussed are given below.
Let’s discuss these methods one by one.
Method 1-Using stoi( ) function
The stoi() function takes a string as an argument and returns its value. Let’s understand this with the help of an example.
#include <iostream>
using namespace std;
int main() {
string str="123";
cout<<stoi(str)<<endl;
string str1="123abd";
cout<<stoi(str1);
return 0;
}
Output
123 123
Method 2-Using atoi( ) function
The atoi() function takes a character array or string literal as an argument and returns its value. Let’s understand this with the help of an example.
#include <bits/stdc++.h>
using namespace std;
int main() {
const char* str1 = "123";
cout<<atoi(str1)<<endl;
const char* str2= "123 geek";
cout<<atoi(str2)<<endl;
return 0;
}
Output
123 123
So these are the methods to convert a string to a number in c++.
The list of C++ Example Programs include swapping number, addition, multiplication of two numbers, factorial of a number and many more. Interested people can get the cpp code to get a clear idea on the programming language.