Pages

Thursday, 27 February 2020

Chapter 11 // Exercise 4 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

Chapter 11 // Exercise 4

Write a program called multi_input.cpp that prompts the user to enter several
integers in any combination of octal, decimal, or hexadecimal, using the 0
and 0x base suffixes; interpret the numbers correctly; and converts them to
decimal form. Then your program should output the values in properly spaced
columns like this:
0x43 hexadecimal converts to 67 decimal
0123 octal converts to 83 decimal
  65         decimal converts to 65 decimal


The useful item I learnt from this exercise is that stoi() takes in 3 parameters, the first is the string, the second is a size_t pointer (used for finding the next value) and last is a number which indicates the base. I noticed that when you use stoi() on an int, the base is default set to 10 (deicmal), therefore it cut off the 0 and 0x, even if the cout stream was set to oct and hex. To convert the number correctly, set the base to 0 as this will check for all 3 bases.

If you just want to check for oct, set the base to 8 and hex to 16. Other than that, the hardest part was getting it to output with all the fields lined up. I really hate that setw().

No comments:

Post a Comment