0

I'm working on a small "Time" functions library just to learn more about how to work with C++ and functions in general.

I'm having a function that is called Time(int hh, int mm, int sec)

I want if the user enters Time(11, 9, 14) I want to store this values in memory as hh = 11; mm = 09; sec = 14; to be used later on.

I know that if I were to use a cout I could have used cout << setw(2) << setfill('0') << mm << endl;

But now I want to directly store the value as an int, how do I do this?`

I tried time = (tt > 10) ? 0 + mm : mm; But i guess this is just like doing basic addition 0+9 = 9.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Petter Östergren
  • 973
  • 4
  • 14
  • 27
  • Yes, it's doing basic addition. The int is not stored as a string in memory and doesn't know anything about leading zeroes. – Ted Lyngmo Oct 24 '18 at 09:44

1 Answers1

6

Don't.

A number is a number.

You are storing the value "nine". This can be written as a decimal literal 9, or an octal literal 010, or a hex literal 0x09, or a hex literal 0x0000000009, or the English "nine", or the French "neuf"…

…or as the formatted, zero-padded string "09" which is possible in C++ but utterly pointless as you sacrifice direct access to arithmetic, lose value validation, and now have to convert it back to a number to do anything interesting with it.

The value you're looking for is already there (actually internally stored as as sequence of binary bits). The information "zero-pad it to two decimal digits" is not part of the value, but part of a possible representation on screen.

Just store 9 in your int and format it when you want to output it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055