gpt4 book ai didi

c++ - 使用 cout 和字符串格式化列

转载 作者:行者123 更新时间:2023-11-30 03:51:16 26 4
gpt4 key购买 nike

晚上好!我希望我能请您协助格式化 cout 语句中的字符串。

目标是让所有列左对齐,最大宽度为 colWidth

在下面的输出中,您会注意到列宽按预期执行,除非字符串长度低于列宽(与 list 项 3 一样)。如果我将 string(strArray[i].begin(), strArray[i].begin() + colWidth) 替换为 strArray[i],则会发生完全相反的情况max 列以下的任何字符串元素都可以,但其他任何内容都会溢出并推出文本。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
string strArray[20] = {"mumblemumble1","mumblemumblemumble2","mumble3","mumblemumblemumblemumble4","mumblemumblemumble5","mumble6","mumblemumblemumblemumble7","mumblemumblemumble8","mumble9","mumblemumblemumblemumble10","mumblemumble11","mumblemumblemumble12","mumble13","mumblemumblemumblemumble14","mumblemumblemumble15","mumblemumble16","mumblemumblemumble17","mumble18","mumblemumblemumblemumble19","mumblemumblemumble20"};
int cols = 2; // The number of columns to display
int colWidth = 10; // Width allowed for title output
int colCount = 0; // Used with mod (%) to provide a new line when needed

cout << endl << endl << "Number of titles in inventory: " << 20;
cout << endl << endl;

for(int i = 0; i < 20; i++)
{
cout << setw(4) << right << (i + 1) << ") " << left << setw(colWidth) << string(strArray[i].begin(),strArray[i].begin() + colWidth);
if ((i+1) % cols == 0)
cout << endl;
}

return 1;
}

产生以下输出:

Number of titles in inventory: 20

1) mumblemumb 2) mumblemumb
3) mumble3 4) mumblemumb
5) mumblemumb 6) mumble6
7) mumblemumb 8) mumblemumb
9) mumble9 10) mumblemumb
11) mumblemumb 12) mumblemumb
13) mumble13 14) mumblemumb
15) mumblemumb 16) mumblemumb
17) mumblemumb 18) mumble18
19) mumblemumb 20) mumblemumb

最佳答案

此代码 string(strArray[i].begin(),strArray[i].begin() + colWidth) 在字符串短于 10 个字符时抛出异常('mumble3' 为例子)。

将您的 for 循环更改为:

for (int i = 0; i < 20; i++)
{
string str = strArray[i];
while (str.size() < colWidth) {
str = str + " ";
}
cout << setw(4) << right << (i + 1) << ") " << left << setw(colWidth) << string(str.begin(), str.begin() + colWidth);
if ((i + 1) % cols == 0)
cout << endl;
}

关于c++ - 使用 cout 和字符串格式化列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com