Open In App

Convert Octal String to Integer using stoi() Function in C++ STL

The octal numeral system, or oct for short, is the base-8 number system and uses the digits 0 to 7, that is to say, 10 octal represents eight, and 100 octal represents sixty-four.

How to Convert Octal String To Integer in C++?

We can use an in-built library function stoi() which stands for String to Integer. This is a Standard Library Function. stoi() function is used to convert a given string of any format is it binary, or octal that string can be converted to an integer.



Syntax:

int num = stoi(string_variable_name, [size_t* i] , int base); 

Parameters:



Return Value: This STL function returns an integer value.

Example 1:




// C++ program to convert octal string to integer
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    string oct_str = "124570";
    int number = 0;
  
    number = stoi(oct_str, 0, 8);
    cout << "Octal string: " << oct_str << endl;
    cout << "number: " << number << endl;
  
    return 0;
}

Output
Octal string: 124570
number: 43384

 Example 2:




// C++ program to convert octal string to integer
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    string octal_str = "54689";
    int number = 0;
  
    number = stoi(octal_str, 0, 8);
    cout << "Octal string: " << octal_str << endl;
    cout << "number: " << number << endl;
  
    return 0;
}

Output
Octal string: 54689
number: 358

Article Tags :