[英]C++ setw() function does not cater for character output width on screen
IDE 二手 Eclipse
據說使用 setw() 和 setfill() function 使用 cout 格式化您的文本。 我試過了,但是如果你看到屏幕上的文本沒有對齊,因為讓我們在第一行說編譯器的作用是
輸入注冊號並用 - 字符填寫 rest
but if you see image attached link, width of R character etc is not equal to - character's width that is why the output is misaligned, is it eclipse output setting? (output 如果復制粘貼到 NOTEPAD++ 文本文件中,則對齊,為什么?) 。 有人可以告訴我如何解決嗎?
無論有多少列或是否將 - 字符替換為空格字符,我都希望它對齊
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main(){
// Weird. Size of R character on screen is not equal to - that is why misalignment
const char separator = '-';
const int nameWidth = 20;
const int numWidth = 20;
// Headings
cout << left << setw(nameWidth) << setfill(separator) <<"Reg No." << left << setw(nameWidth)
<< setfill(separator) << "First Name" << left << setw(nameWidth) << setfill(separator) <<
"Last Name"<< endl;
// Data column
cout << left << setw(numWidth) << setfill(separator) << 123 << left << setw(numWidth) <<
setfill(separator) << "JohnPeter" << left << setw(numWidth) << setfill(separator) <<
"" << left << setw(numWidth) << endl;
cout << left << setw(numWidth) << setfill(separator) << 123123 << left << setw(numWidth) <<
setfill(separator) << "Peter" << left << setw(numWidth) << setfill(separator) <<
"testingLastName" << left << setw(numWidth) << endl;
cout << left << setw(numWidth) << setfill(separator) << 11233333 << left << setw(numWidth) <<
setfill(separator) << "a" << left << setw(numWidth) << setfill(separator) <<
"a" << left << setw(numWidth) << endl;
return 0;
}
code output is not aligned see eclipse c++ output image Eclipse C++ output
這是正確的。 std::setw
實際上並不調整轉換的可見寬度; 它會調整字符數,假設 output 正在使用等寬字體(即所有字符寬度相同的字體)查看。
因此,您需要配置 Eclipse 的控制台以使用等寬字體。 (這將在“首選項”菜單中的某個位置;希望它相當容易找到。)但請注意,在可打印的 ascii 范圍之外,有很多字符不會呈現為等寬字體的“恆定寬度”。 例如,漢字符通常是雙倍寬度,並且組合重音符號和許多控制字符的寬度為 0。因此,表格控制台 output 變得越來越難以實現。
如果你想要更漂亮的 output 並且你不想 go 編寫圖形界面的麻煩 - 如果你想要做的只是呈現一個具有對齊列的表格,那么這將是很多工作 - 你最好的選擇可能是生成 HTML 並通過 HTML 渲染器(例如 Z2567A5EC9705EB7AC2C98403 瀏覽器)輸入程序 output。
我在 Linux 上使用 GCC 進行了測試,它已對齊,請參閱我的結果您的結果具有正確的字符數。 未對齊的外觀是由您使用的字體引起的,它不是等寬的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.