【发布时间】:2019-08-27 21:10:10
【问题描述】:
我的程序应该根据用户指定的内容对齐输入的文本,到目前为止,我已经让它改变宽度但不对齐文本(左、右、中心)。我见过<iomanip>,但对我来说没有帮助。到目前为止我得到的代码是
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
using namespace std;
string repeatChar(char c, int n) {
string out;
for (; n > 0; n--) {
out.push_back(c);
}
return out;
}
vector<string> getInput() {
vector<string> output;
string line;
cout << "Enter text, empty return will quit the input" << endl;
do {
cout << "> ";
getline(cin, line);
if (line.empty())
continue;
istringstream in(line);
string word;
while (in.good()) {
in >> word;
if (!word.empty())
output.push_back(word);
}
} while (!line.empty());
return output;
}
void printLine(vector<string>::iterator start, vector<string>::iterator end,
int width) {
if(start == end)
return;
int chars = 0;
int spaces = -1;
vector<string> currentLine;
for (; start != end; start++) {
string &word = *start;
int newchars = chars + word.length();
int newspaces = spaces + 1;
if (newchars + newspaces <= width) {
currentLine.push_back(word);
chars = newchars;
spaces = newspaces;
} else
break;
}
cout << '|';
if (spaces <= 0) {
cout << currentLine[0] << repeatChar(' ', (width - chars));
} else {
int spaceWidth = (width - chars) / spaces;
int extraWidth = (width - chars) % spaces;
int i;
for (i = 0; i < currentLine.size() - 1; i++) {
cout << currentLine[i];
cout << repeatChar(' ', spaceWidth);
if (extraWidth > 0) {
cout << ' ';
extraWidth--;
}
}
cout << currentLine[i];
}
cout << '|' << endl;
printLine(start, end, width);
return;
}
void printJustify(vector<string> words, int width) {
cout << '+' << repeatChar('-', width) << '+' << endl;
printLine(words.begin(), words.end(), width);
cout << '+' << repeatChar('-', width) << '+' << endl;
}
int main() {
vector<string> input = getInput();
int maxWidth = 0;
for (int i = 0; i < input.size(); i++) {
maxWidth = (input[i].length() > maxWidth) ? input[i].length() : maxWidth;
}
int width;
do {
cout << "> Enter width of text and align(Left, Right, Center) ";
cin >> width;
if (width == 0)
continue;
width = (width < maxWidth) ? maxWidth : width;
printJustify(input, width);
} while (width > 0);
return 0;
}
但这只会调整宽度,所以我的输出是
Enter text, empty return will quit the input
> There are many types of Parrots in the world,
> for example, African Greys, Macaws,
> Amazons. And much much more.
>
> Enter width of text and align(Left, Right, Center) 30
+------------------------------+
|There are many types of|
|Parrots in the world, for|
|example, African Greys,|
|Macaws, Macaws, Amazons. And|
|much much more. more.|
+------------------------------+
> Enter width of text and align(Left, Right, Center)
这很好,但我还需要根据用户输入的内容来对齐左、右、中心。我用过<iomanip>,但这并没有用。如何使输出左对齐、右对齐或居中?
【问题讨论】:
-
我唯一的想法是因为你已经有了你的盒子的大小,例如
"| |",为什么不把它变成一个字符串。对于右对齐文本,不必担心将输入拆分为单词。你知道开始和结束字符被取走。因此,为了填充右对齐,只需在输入字符串上使用反向迭代器来写入那些从"| |"中倒数第二个位置开始的字符。 -
我假设您没有使用
<iomanip>是因为您不被允许,而不是因为您不知道如何使用?<iomanip>让事情变得容易得多。