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

4
在这个代码中,我希望从0到1000以特定格式打印数字,并在其前添加固定文本,如下所示:
Test 001 Test 002 Test 003 ... Test 999
但是,我不想将其显示为:
Test 1 Test 2 ... Test 10 ... Test 999
以下的 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;
}

我认为你需要在 i 前面加上 setwsetfillstd::cout << std::setfill('0') << std::setw(3) << i; - triple_r
1个回答

10

setfillsetw 操作符只对下一个输出操作有效。因此,在您的情况下,您要将其设置为TEXT的输出。

相反,请执行例如:

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

对于现在阅读此文的读者:setfill 实际上适用于流上的所有后续输出操作。例如尝试以下代码: std::cout << std::setfill('-') << std::setw(20) << "hi" << '\n' << std::setw(20) << "bar" << '\n'; - Sebastiaan Alvarez Rodriguez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接