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++ 控制台输出


- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01