Open In App

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

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • string_variable_name: It is the input string.
  • size t* i: It is an optional parameter (pointer to the object whose value is set by the function), its default value is 0, or we can assign it to nullptr.
  • int base: specifies the radix to determine the value type of the input string. Its default value is 10, it is also an optional parameter. For Octal its value is 8.

Return Value: This STL function returns an integer value.

Example 1:

C++




// 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++




// 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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads