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
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01