Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ output formatting using setw and setfill

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;
}
like image 214
djnotes Avatar asked Dec 25 '22 10:12

djnotes


1 Answers

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;
like image 106
Some programmer dude Avatar answered Jan 09 '23 18:01

Some programmer dude