Answers for "how to turn a string into an int c++"

C++
3

string to int in c++

#include <iostream>
#include <string>
using namespace std;
int main() {
 
    string s = "10";
 
    try
    {
        int i = stoi(s);
        cout << i << '\n';
    }
    catch (invalid_argument const &e)
    {
        cout << "Bad input: std::invalid_argument thrown" << '\n';
    }
    catch (out_of_range const &e)
    {
        cout << "Integer overflow: std::out_of_range thrown" << '\n';
    }
 
    return 0;
}
Posted by: Guest on December-10-2020
0

how to convert string to int in c++

string s = "123";
int n = s.size();
int num = 0;
 for(int i = 0 ; i<n;i++)//this what stoi built function do XD
 {
  num = num*10+(s[i]-'0');
 }
Posted by: Guest on July-12-2021
0

string to int c++

#include <iostream>
#include <string>

// namespace because why not
namespace dstd
{
    int StringtoInt(std::string str)
    {
        int multiplier = 1;
        int sum = 0;
        for(int i = str.size() - 1;i >= 0; i--)
        {
            switch(str[i])
            {
                case '0':
                sum += 0;
                break;
                case '1':
                sum += 1 * multiplier;
                break;
                case '2':
                sum += 2 * multiplier;
                break;
                case '3':
                sum += 3 * multiplier;
                break;
                case '4':
                sum += 4 * multiplier;
                break;
                case '5':
                sum += 5 * multiplier;
                break;
                case '6':
                sum += 6 * multiplier;
                break;
                case '7':
                sum += 7 * multiplier;
                break;
                case '8':
                sum += 8 * multiplier;
                break;
                case '9':
                sum += 9 * multiplier;
                break;
                case '-':
                sum *= -1;
                break;
                case ' ':
                continue;
                case 
            }
            multiplier *= 10;
        }

        return sum;
    }
}

int main()
{
  //just an example of how to use the function
    int a = dstd::StringtoInt("1992");
  	std::cout<<a<<'\n';
}
Posted by: Guest on March-03-2022

Code answers related to "how to turn a string into an int c++"

Browse Popular Code Answers by Language