Formatting C++ console output(格式化 C++ 控制台输出)
问题描述
我一直在尝试将输出格式化到控制台的最长时间,但实际上并没有发生任何事情.我一直在尝试尽可能多地使用 iomanip 和 ofstream& 输出函数.
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++ 控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:格式化 C++ 控制台输出
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
