Convert String to Number in C++
1. Using Built-in Functions:
- Use the built-in function to convert the string to a number.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "123";
// Step 1
int num = stoi(str);
cout << num << endl;
return 0;
}
Output
123
2. String Concatenation:
- Check if the string represents a negative number and set a flag.
- Iterate over each character of the string and convert it to its corresponding numerical value.
- Calculate the numerical value using the digits.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "-123";
int sign = 1, num = 0;
// Step 1
if (str[0] == '-') {
sign = -1;
str = str.substr(1);
}
// Step 2
for (char c : str) {
num = num * 10 + (c - '0');
}
// Step 3
num *= sign;
cout << num << endl;
return 0;
}
Output
-123
How to Convert String to Number
Given a string representation of a numerical value, convert it into an actual numerical value. In this article, we will provide a detailed overview about different ways to convert string to number in different languages.
Table of Content
- Convert String to Number in C
- Convert String to Number in C++
- Convert String to Number in Java
- Convert String to Number in Python
- Convert String to Number in C#
- Convert String to Number in JavaScript