1

I want to print out a time like minutes:second.miliseconds . Think about that time is 4 minutes 2 seconds 65 miliseconds
instead of writing it like 4:2.65 I want to write it like 4:02.065 how can I do that ?

2 Answers2

6

If you use iostream or stringstream:

#include <iostream>
#include <iomanip>
[...]
int val = 1;
std::cout << std::setw(2) << std::setfill('0') << val << std::endl;
[...]

std::setw sets the width of the following element.

std::setfill sets the character which fills the empty space.

user6556709
  • 1,272
  • 8
  • 13
5

You'd use iomanip for that

#include <iomanip>
#include <iostream>
//intermediate code goes here
std::cout << minutes << ":" << std::setfill('0') << std::setw(2) << seconds << "." << std::setw(3) << milliseconds << std::endl;
Pierce Griffiths
  • 733
  • 3
  • 15
  • Worth noting that some I/O manipulators are "just for the next output", and others are "sticky" until changed. Some people instead do the formatting to a stringstream and then output the results in the desired stream; others save/restore the state of the stream (Boost has a nice helper utility to do that). – Eljay Apr 27 '19 at 16:18