格式化 C++ 控制台输出 [英] Formatting C++ console output

查看:26
本文介绍了格式化 C++ 控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将输出格式化到控制台的最长时间,但实际上并没有发生任何事情.我一直在尝试尽可能多地使用 iomanipofstream& 输出函数.

I've been trying to format the output to the console for the longest time and nothing is really happening. I've been trying to use as much of iomanip as I can and the ofstream& out functions.

void list::displayByName(ostream& out) const
{
    node *current_node  = headByName;

    // I have these outside the loop so I don't write it every time.

    out << "Name		" << "	Location" << "	Rating " << "Acre" << endl;
    out << "----		" << "	--------" << "	------ " << "----" << endl;

    while (current_node)
    {
        out << current_node->item.getName() // Equivalent tabs don't work?
            << current_node->item.getLocation()
            << current_node->item.getAcres()
            << current_node->item.getRating()
            << endl;

        current_node = current_node->nextByName;
    }

    // The equivalent tabs do not work because I am writing names,
    // each of different length to the console. That explains why they
    // are not all evenly spaced apart.
}

我可以使用它们来使它们彼此正确对齐吗?我调用的函数是不言自明的,并且长度不同,因此彼此之间不能很好地对齐.

Is their anything that I can use to get it all properly aligned with each other? The functions that I'm calling are self-explanatory and all of different lengths, so that don't align very well with each other.

我已经尝试了 iomanip 中的所有内容.

I've tried just about everything in iomanip.

推荐答案

您可以编写一个始终将相同数量的字符打印到标准输出的过程.

You can write a procedure that always print the same number of characters to standard output.

类似:

string StringPadding(string original, size_t charCount)
{
    original.resize(charCount, ' ');
    return original;
}

然后在你的程序中这样使用:

And then use like this in your program:

void list::displayByName(ostream& out) const
{
    node *current_node  = headByName;

    out << StringPadding("Name", 30)
        << StringPadding("Location", 10)
        << StringPadding("Rating", 10)
        << StringPadding("Acre", 10) << endl;
    out << StringPadding("----", 30)
        << StringPadding("--------", 10)
        << StringPadding("------", 10)
        << StringPadding("----", 10) << endl;

    while ( current_node)
    {
        out << StringPadding(current_node->item.getName(), 30)
            << StringPadding(current_node->item.getLocation(), 10)
            << StringPadding(current_node->item.getRating(), 10)
            << StringPadding(current_node->item.getAcres(), 10)
            << endl;
        current_node = current_node->nextByName;
    }
}

这篇关于格式化 C++ 控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆