這是我的代碼 有誰知道我如何格式化它,使其看起來更像一個正方形,而不是由于每個元素中的字符大小不同。
1
int main() {
string a[4][4]= {{"\xC9","\xCD","\xCD","\xBB"},
{"\xBA","p1","p2","\xBA"},
{"\xBA","100","p3","\xBA"},
{"\xC8","\xCD","\xCD","\xBC"}};
printSquare(a);
這是我的代碼,但輸出似乎很有趣

uj5u.com熱心網友回復:
這里沒有真正的捷徑:你必須把它們都帶到相同的長度。選擇哪個長度:硬。您可能首先必須制作所有行,然后找到最長的行,將所有行的格式設定為具有相同的長度,然后制作頂部和底部欄。
您可以使用標準 C 中的 iostreams / stringstream來做到這一點。但這真的很痛苦。iostreams 根本就不是一個好的輸出格式庫。
我建議使用支持格式字串的fmtlib。所以你可以先格式化所有的行,并保存最長的長度
#include "fmt/format.h"
#include "fmt/ranges.h"
#include <algorithm>
#include <string>
#include <vector>
int main() {
std::vector<std::vector<std::string>> data{
{"p1", "p2"}, {"100", "p3"}, {"very long string"}};
unsigned int longest_row = 0;
for (const auto &row : data) {
const std::string this_row =
fmt::format("{}", fmt::join(row.begin(), row.end(), ""));
unsigned int rowlength = this_row.length();
longest_row = std::max(longest_row, rowlength);
}
// Explanation: Print corner - empty string - corner, but pad "empty string"
// longest row times with "middle piece" > is for right-aligned padding
// (doesn't matter for empty string)
fmt::print("╔{:═>{}}╗\n", "", longest_row);
for (const auto &row : data) {
// ^ is for centered padding
// fill with " " (we could omit this, but I think it's clearer)
const std::string this_row =
fmt::format("{}", fmt::join(row.begin(), row.end(), ""));
fmt::print("║{: ^{}}║\n", this_row, longest_row);
}
fmt::print("╚{:═>{}}╝\n", "", longest_row);
}
評論:
- 用 std::vectors 替換了你的字串陣列。只是更方便。
- 無需使用轉義序列在字串中包含 unicode 字符,除非您的編譯器很爛。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366755.html
