简体   繁体   中英

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;
}

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 eg

oFile << TEXT << std::setfill('0') << std::setw(3) << i << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM