我是C++的新手,想知道是否有更优雅的方法可以打印出以下内容:
Celsius Kelvin Fahrenheit Reaumur
-------------------------------------
我想你可以做
cout << "Celsius Kelvin Fahrenheit Reaumur" << endl << "-------------------------------------";
但它看起来不太好。在阿达,你可以做"Width"
。cpp中有类似的运算符吗?你能不能不只是做setfill('-')
和你想打印的"-"的数量?
非常感谢任何帮助
以下是生产这条线的另外两种方法:
std::cout << "-------------------------------------n";
std::setfill
+std::setw
:
#include <iomanip>
std::cout << std::setfill('-') << std::setw(38) << 'n';
使用std::string
:
#include <string>
std::cout << std::string(37, '-') << 'n';
演示
您可以(也可能应该(使用std::format
。另请参阅fmtlib/fmt
库:
-
https://en.cppreference.com/w/cpp/utility/format/format
-
https://www.modernescpp.com/index.php/std-format-in-c-20
-
https://github.com/fmtlib/fmt
format和fmtlib都使用格式规范":
- https://en.cppreference.com/w/cpp/utility/format/format
另请参阅这个问题,它有几个相关的答案:
- std::字符串格式,类似于sprintf
你可以很容易地调整它,使其符合你的需求(为了清晰起见,我故意做了一些缺陷(:
#include <fmt/core.h>
int main() {
int const width = 12;
// See https://en.cppreference.com/w/cpp/utility/format/format
// ^ centres the field (with default space fill)
// -^ centres the field with "-" fill
// 12 and 52 are specific field widths.
// inner {} means the field width is provided by the next parameter
fmt::print("_{:^{}} {:^{}} {:^{}} {:^12}_n-{:-^52}n",
"Celsius", width,
"Kelvin", width,
"Farenheit", width,
"Reaumur",
"=");
}
输出:
_ Celsius Kelvin Farenheit Reaumur _
--------------------------=--------------------------
FmtLib演示:https://godbolt.org/z/463xWvx5P
格式化演示:https://godbolt.org/z/MP9sac7ba(谢谢Ted(
非常喜欢将其分离以便于重复使用和阅读。示例:
std::ostream & draw_heading(std::ostream & out,
const std::string & heading)
{
char old_fill = out.fill('-');
std::streamsize old_width = out.width();
out << h.mHeading << 'n'
<< std::setw(h.mHeading.size() + 1) << 'n';
out.width(old_width);
out.fill(old_fill);
return out;
}
只进行写入并将写入任何输出流。它返回一个对流的引用,这样就可以很容易地测试它的成功或链接。
基本用途:
draw_heading(std::cout, "Celsius Kelvin Fahrenheit Reaumur");
丑陋的东西现在被隐藏在主逻辑之外,它可以继续做任何该死的工作
您可以使用文字字符串功能:
#include <string>
#include <iostream>
int main()
{
std::cout << R"(
This is a line of text with an underline
----------------------------------------
)";
}
这允许您添加所有想要的显式字符(包括换行符(,这使得大块文本的布局(相对而言(在代码中更容易实现。
我只希望R"(
忽略第一个换行符,如果它是该行中唯一的字符。但它看起来仍然比更好
cout << "Celsius Kelvin Fahrenheit Reaumurn"
<< "------------------------------------n";
或
cout << "Celsius Kelvin Fahrenheit Reaumurn"
<< std::string(38, '-') << "n";