在表格中格式化输出,C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6755250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format output in a table, C++
提问by JT White
How can I output data to the console in a table in C++? There's a question for this in C#, but I need it in C++.
如何将数据输出到 C++ 表格中的控制台?在 C# 中有一个问题,但我在 C++ 中需要它。
This, except in C++: How To: Best way to draw table in console app (C#)
这,除了在 C++ 中:How To: Best way to draw table in console app (C#)
采纳答案by Tim S.
Can't you do something very similar to the C# example of:
你不能做一些与 C# 示例非常相似的事情:
String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);
Like:
喜欢:
printf("|%5s|%5s|%5s|%5s|", arg0, arg1, arg2, arg3);
Here's a reference I used to make this: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
这是我用来做这个的参考:http: //www.cplusplus.com/reference/clibrary/cstdio/printf/
回答by Dawson
Here's a small sample of what iomanip has:
以下是 iomanip 的一小部分示例:
#include <iostream>
#include <iomanip>
int main(int argc, char** argv) {
std::cout << std::setw(20) << std::right << "Hi there!" << std::endl;
std::cout << std::setw(20) << std::right << "shorter" << std::endl;
return 0;
}
There are other things you can do as well, like setting the precision of floating-point numbers, changing the character used as padding when using setw, outputting numbers in something other than base 10, and so forth.
您还可以执行其他操作,例如设置浮点数的精度、在使用 setw 时更改用作填充的字符、以非 10 为基数输出数字等。
回答by Yoav Kleinberger
I couldn't find something I liked, so I made one. Find it at https://github.com/haarcuba/text-table
我找不到我喜欢的东西,所以我做了一个。在https://github.com/haarcuba/text-table找到它
Here's an exmaple of its output:
这是其输出的示例:
+------+------+----+
| |Sex | Age|
+------+------+----+
|Moses |male |4556|
+------+------+----+
|Jesus |male |2016|
+------+------+----+
|Debora|female|3001|
+------+------+----+
|Bob |male | 25|
+------+------+----+
回答by Vijay Kumar Kanta
Check the column value length and also keep the length of value in mind to format.
检查列值长度并记住值的长度以进行格式化。
printf(" %-4s| %-10s| %-5s|\n", "ID", "NAME", "AGE");
See how MySQL shell interface was designed, it will give you a good idea.
看看 MySQL shell 界面是如何设计的,它会给你一个好主意。