4

In this code, I want to have numbers printed in special format starting from 0 to 1000 preceding a fixed text, like this:

Test 001
Test 002
Test 003
...
Test 999

But, I don't like to display it as

Test 1
Test 2
...
Test 10
...
Test 999

What is wrong with the following C++ program making it fail to do the aforementioned job?

#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using  namespace std;

const string TEXT = "Test: ";

int main()
{

    const int MAX = 1000;
    ofstream oFile;

    oFile.open("output.txt");


    for (int i = 0; i < MAX; i++) {
        oFile << std::setfill('0')<< std::setw(3) ;
        oFile << TEXT << i << endl;
    }


    return 0;
}
Mehdi Haghgoo
  • 3,144
  • 7
  • 46
  • 91
  • I think you need to put `setw` and `setfill` just beofre `i`: `std::cout << std::setfill('0') << std::setw(3) << i;`. – triple_r Jan 11 '16 at 20:38

1 Answers1

10

The setfill and setw manipulators is for the next output operation only. So in your case you set it for the output of TEXT.

Instead do e.g.

oFile << TEXT << std::setfill('0') << std::setw(3) << i << endl;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • For those of you reading this now: [`setfill`](https://en.cppreference.com/w/cpp/io/manip/setfill) actually works for **ALL** following output operations on the stream. Try with e.g: `std::cout << std::setfill('-') << std::setw(20) << "hi" << '\n' << std::setw(20) << "bar" << '\n';` – Sebastiaan Alvarez Rodriguez Jun 07 '21 at 20:56