Convert String to Number in C++

1. Using Built-in Functions:

  • Use the built-in function to convert the string to a number.
C++
#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.
C++
#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

Similar Reads

Convert String to Number in C:

1. Using Built-in Functions:...

Convert String to Number in C++:

1. Using Built-in Functions:...

Convert String to Number in Java:

1. Using Built-in Functions:...

Convert String to Number in Python:

1. Using Built-in Functions:...

Convert String to Number in C#:

1. Using Built-in Functions:...

Convert String to Number in JavaScript:

1. Using Built-in Functions:...

Conclusion:

Converting a string to a number involves interpreting the characters in the string as numerical values. This typically requires iterating through each character, converting it to its numeric equivalent, and considering any sign indicators. By following this process, strings can be transformed into their corresponding numeric representations, facilitating numerical operations and calculations in programming....