C++ output formatting using setw and setfill

£可爱£侵袭症+ 提交于 2019-12-10 21:08:47

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/34730587/c-output-formatting-using-setw-and-setfill

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!