晚上好!我希望我可以在cout声明中请求你帮助格式化字符串。
目标是让所有列左对齐,最大宽度为colWidth
。
在下面的输出中,除非字符串长度低于列宽(与库存项目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
答案 0 :(得分:2)
当字符串短于10个字符时,此代码string(strArray[i].begin(),strArray[i].begin() + colWidth)
会引发异常(例如,&#39; mumble3&#39;)。
将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;
}