格式化C ++控制台输出 [英] Formatting C++ Console Output

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

问题描述

我一直在尝试将输出格式化到控制台最长的时间,没有什么是真的发生。我一直试图使用尽可能多的 iomanip ,我可以和 ofstream& out函数。

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 dont write it everytime.

 out << "Name\t\t" << "\tLocation" << "\tRating " << "Acre" << endl;
 out << "----\t\t" << "\t--------" << "\t------ " << "----" << endl;

 while ( current_node )
 {
  out << current_node->item.getName()// equivalent tabs dont 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 Im calling are self-explanatory and all of different lengths, so that don't align very well with each other.

c>

推荐答案

您可以编写一个过程总是在标准输出中打印相同数量的字符。
类似

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

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天全站免登陆