1

What is the easiest way to convert string holding octal number into string holding decimal representation of the same number?

I could convert it into int value using strtol, then convert into string again using stringstream:

string oct_number("203"); 

// converts into integer
int value = strtol(oct_number.c_str(), NULL, 8);

// converts int to decimal string
stringstream ss;
ss  << value;
string dec_number = ss.str();

But: is there any quicker way to do it? I have a rather poor understanding of the stringstream class, am I missing something?

2 Answers 2

2
std::string result;
Try
{
   result = std::to_string( std::stoi( oct_number, 0, 8 ) );
}
catch ( ... )
{
//...
}
Sign up to request clarification or add additional context in comments.

4 Comments

He said he wanted to convert it to decimal so shouldn't it just be std::stoi(oct_number)?
@0x499602D2 He wants to convert one string into another string.
He said he wanted the decimal representation if I'm not mistaken.
@0x499602D2 Read his post one more. It is clear enough.
0

In c++11 you can use string dec_number = to_string (value);. Also you can use sprintf but you will need some buffer:

char buf[64];
sprintf(buf,"%d",value);
string dec_number = buf;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.