在 C++ 中使用 cout 打印输出中的绝对定位?
如何使用 cout 获得“绝对定位”的列,使文本左对齐并右对齐数字?
#include <iostream>
#include <iomanip>
using namespace std;
struct Human {
char name[20];
char name2[20];
char name3[20];
double pts;
};
int main() {
int i;
Human myHumen[3] = {
{"Mr", "Alan", "Turing", 12.25},
{"Ms", "Ada", "Lovelace", 15.25},
{"Sir", "Edgar Allan", "Poe", 45.25}
};
cout << "Name1" << setw(22) << "Name2" << setw(22) << "Name3" << setw(22) << "Rating" <<endl;
cout << "-----------------------------------------------------------------------\n";
for(i = 0; i < 3; i++) {
cout << myHumen[i].name << setw(22) << myHumen[i].name2 << setw(22) << myHumen[i].name3 << setw(20) << myHumen[i].pts << endl;
}//this didn't do nice printouts, with leftalign for text and rightalign with numbers
}
How do you get "absolutely positioned" columns with cout, that leftaligns text and right-aligns numbers?
#include <iostream>
#include <iomanip>
using namespace std;
struct Human {
char name[20];
char name2[20];
char name3[20];
double pts;
};
int main() {
int i;
Human myHumen[3] = {
{"Mr", "Alan", "Turing", 12.25},
{"Ms", "Ada", "Lovelace", 15.25},
{"Sir", "Edgar Allan", "Poe", 45.25}
};
cout << "Name1" << setw(22) << "Name2" << setw(22) << "Name3" << setw(22) << "Rating" <<endl;
cout << "-----------------------------------------------------------------------\n";
for(i = 0; i < 3; i++) {
cout << myHumen[i].name << setw(22) << myHumen[i].name2 << setw(22) << myHumen[i].name3 << setw(20) << myHumen[i].pts << endl;
}//this didn't do nice printouts, with leftalign for text and rightalign with numbers
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用“左”和“右”操纵器:
带有文本+数字的示例:
打印:
You use the "left" and "right" manipulators:
An example with text + numbers:
Which prints:
这会有点不受欢迎,但您可以使用 printf 来执行这种快速程序。格式化字符串更容易理解和使用(对于熟悉 iostreams 和 printf 的人来说)。
混合 cout 和 printf 是安全的(默认情况下,请参见 std::sync_with_stdio),并且一个好的编译器也可以为您检查格式字符串的类型(gcc 中的 -Wall)。
This is going to be slightly unpopular, but you can just use printf for this kind of quick program. The formatting strings are easier to understand and use (given someone who groks both iostreams and printf).
It is safe (by default, see std::sync_with_stdio) to mix cout and printf, and a good compiler can check the types of the format strings for you, too (-Wall in gcc).