C++;使用cout设置列 我刚刚开始学习C++,我很好奇它是用CUT来形成输出的一种方式,所以它在列中看起来很好,结构也很好。
比如说C++;使用cout设置列 我刚刚开始学习C++,我很好奇它是用CUT来形成输出的一种方式,所以它在列中看起来很好,结构也很好。,c++,multiple-columns,cout,setw,C++,Multiple Columns,Cout,Setw,比如说 string fname = "testname"; string lname = "123"; double height = 1.6; string fname2 = "short"; string lname2 = "123"; double height2 = 1.8; cout << "Name" << setw(30) << "Height[m]" << endl; c
string fname = "testname";
string lname = "123";
double height = 1.6;
string fname2 = "short";
string lname2 = "123";
double height2 = 1.8;
cout << "Name" << setw(30) << "Height[m]" << endl;
cout << fname + " " + lname << right << setw(20) << setprecision(2) << fixed << height << endl;
cout << fname2 + " " + lname2 << right << setw(20) << setprecision(2) << fixed << height2 << endl
我希望它看起来像这样:
Name Height[m]
testname 123 1.60
short 123 1.80
Name Height[m]
testname 123 1.60
short 123 1.80
我试图解决的问题是,我想把高度放在名字的一个特定位置,但根据名字的长度,高度的值要么远离右边,要么非常接近左边。有办法解决这个问题吗?string fname=“testname”;
string fname = "testname";
string lname = "123";
double height = 1.6;
string fname2 = "short";
string lname2 = "123";
double height2 = 1.8;
cout << left << setw(30) << "Name" << left << "Height[m]" << endl;
cout << left << setw(30) << fname + " " + lname << right << setw(6) << setprecision(2) << fixed << height << endl;
cout << left << setw(30) << fname2 + " " + lname2 << right << setw(6) << setprecision(2) << fixed << height2 << endl;
字符串lname=“123”;
双倍高度=1.6;
字符串fname2=“short”;
字符串lname2=“123”;
双高2=1.8;
cout首先,对于像std::cout
这样的输出流,您无法返回时间并修改已经执行的输出。这是有道理的——想象一下,std::cout
写入了一个文件,因为你用program.exe>test.txt
启动了你的程序,而test.txt
在一个USB驱动器上,而这个USB驱动器同时被断开了连接
所以你必须马上把它做好
基本上有两种方法
您可以假设第一列中的任何条目都不会超过一定数量的字符,这正是您所尝试的。问题是您的setw
位于错误的位置,并且right
应该是left
。流操纵器必须放置在应受影响的元素之前。由于您需要左对齐的列,因此需要左
:
cout << left << setw(20) << "Name" << "Height[m]" << endl;
cout << left << setw(20) << fname + " " + lname << setprecision(2) << fixed << height << endl;
cout << left << setw(20) << fname2 + " " + lname2 << setprecision(2) << fixed << height2 << endl;
您是否应该在第一列的条目中添加“Name”
fname+“”+lname
和fname2+“”+lname2
都可能产生一个空格…@SimonKraemer:这一点很好。我没有发布一个完整的程序,但是这个改变是有意义的。
std::vector<std::string> const first_column_entries
{
"Name",
fname + " " + lname,
fname2 + " " + lname2
};
auto const width_of_longest_entry = std::max_element(std::begin(first_column_entries), std::end(first_column_entries),
[](std::string const& lhs, std::string const& rhs)
{
return lhs.size() < rhs.size();
}
)->size();
// some margin:
auto const column_width = width_of_longest_entry + 3;
std::cout << std::left << std::setw(column_width) << "Name" << "Height[m]" << "\n";
std::cout << std::left << std::setw(column_width) << fname + " " + lname << std::setprecision(2) << std::fixed << height << "\n";
std::cout << std::left << std::setw(column_width) << fname2 + " " + lname2 << std::setprecision(2) << std::fixed << height2 << "\n";