简体   繁体   English

使用setw和setfill进行C ++输出格式化

[英]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: 在这段代码中,我希望在固定文本之前从0到1000开始以特殊格式打印数字,如下所示:

Test 001 测试001
Test 002 测试002
Test 003 测试003
... ...
Test 999 测试999

But, I don't like to display it as 但是,我不喜欢将它显示为

Test 1 测试1
Test 2 测试2
... ...
Test 10 测试10
... ...
Test 999 测试999

What is wrong with the following C++ program making it fail to do the aforementioned job? 以下C ++程序有什么问题导致它无法完成上述工作?

#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. setfillsetw 操纵器仅用于下一个输出操作。 So in your case you set it for the output of TEXT . 因此,在您的情况下,您将其设置为TEXT的输出。

Instead do eg 相反,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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