简体   繁体   English

fstream和setw无法正确对齐输出

[英]fstream and setw not aligning output properly

setw does not seem to be aligning things here for me, and I can't figure out why that is. setw似乎并没有为我调整方向,我不知道为什么会这样。 Inserting \\t does push things to the right, but I'd like to have tighter control over the formatting of the output. 插入\\t确实可以将操作推向右侧,但是我想对输出的格式进行更严格的控制。 Any ideas? 有任何想法吗?

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {

    string name = "Name LastName";
    int age = 27;
    double milesRun = 15.5;

    ofstream outFile;
    outFile.open("text.txt");

    outFile << "Person's name: " << name << setw(12) << "Person's age: " << age << setw(12) << "Miles run: " << milesRun << endl;

    outFile.close();

    return 0;
}

Remember that when using setw , the function is used to declare the area that is about to appear. 请记住,当使用setw ,该函数用于声明即将出现的区域。 Therefore, you can use it to declare static values, such as the text in your information like "Person's Name:" by counting the characters and using that as your value (generally +1 or 2). 因此,您可以通过计算字符并将其用作值(通常为+1或2)来声明静态值,例如"Person's Name:"类的信息中的文本。 Using that as an example, the value would be setw(16) to account for each character + 2 spaces. 以该示例为例,该值将设置为setw(16)以说明每个字符+ 2个空格。 Then you apply another setw value to declare the field to come, choosing a value large enough to accommodate your data. 然后,您应用另一个setw值声明要出现的字段,选择一个足够大的值来容纳您的数据。 Remember to align left so you can see how this affects your output. 请记住left对齐,以便您可以看到它如何影响输出。 In your example, you were aligning right, and while that may give formatted output in some examples, it breaks in others, as you saw. 在您的示例中,您正在对齐,尽管在某些示例中这可能会提供格式化的输出,但在其他示例中却中断了,如您所见。


If you want more space between each data set, then simply increase the width of the field like in this example. 如果要在每个数据集之间留出更多空间,则可以像例中那样简单地增加字段的宽度。 This way everything is left aligned and you have no need for tabs. 这样,所有内容都保持对齐,您无需使用制表符。

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

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