我正在开发一个程序,当用户输入文本时,他们可以指定如何对齐输出。因此,用户将输入文本,然后将询问他们对文本(中心,左,右,然后宽度)所需的对齐和宽度。你如何获得宽度和对齐的代码?到目前为止,我只有获取用户输入的代码,但我不知道如何让程序让用户输入他们的标准(左,右,中心和宽度),然后对齐用户给出的输入。这是我到目前为止所得到的。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
vector<string> text;
string line;
cout << "Enter Your Text:(to start a newline click enter. When done click enter 2 times " << endl;
while (getline(cin, line) && !line.empty())
text.push_back(line);
cout << "You entered: " << endl;
for (auto &s : text)
cout << s << endl;
cout << "Enter Left,Center,Right and Width: ";
return 0;
}
我想也许我必须使用<iomanip>
?但我觉得还有另一种方式。输入就像是。
Hello My Name is Willi
John Doe
and I live in
Kansas.
然后当用户输入对齐时,文本将对齐,因此说用户输入右对齐,宽度为10.输出应该是右边对齐的(就像在文字处理器中一样),宽度应为10空格(我假设是空格)。
这是一个简单的方法。它只是根据对齐方式用空格填充每一行。左对齐基本上是输入文本。您还应该检查对齐宽度是否为>=
而不是输入的最长行。
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> text;
std::vector<std::string> output;
std::string line;
std::string align;
int width;
std::cout << "Enter Your Text (to start a newline click enter. When done click enter 2 times): \n";
while ( std::getline(std::cin, line) && !line.empty() )
text.push_back(line);
std::cout << "You entered:\n\n";
for ( auto &s : text )
std::cout << s << "\n";
std::cout << "Enter Left,Center,Right and Width: ";
std::cin >> align;
std::cin >> width;
for ( auto &s : text ) {
int diff = width - s.size(),
half = diff / 2;
if ( align == "Right" ) {
output.push_back( std::string(diff, ' ') + s );
} else if ( align == "Center" ) {
output.push_back( std::string(half, ' ') + s + std::string(diff - half, ' ') );
} else {
output.push_back( s );
}
}
std::cout << "Aligned Output: \n\n";
for ( auto &s : output )
std::cout << s << "\n";
return 0;
}
测试用例(实际输出有空格,而不是*
):
输入(alignment = Right,width = 10):
Hello my name is John Doe
输出:
**Hello my ***name is **John Doe
输入(alignment = Center,width = 16):
Hello my name is John Doe
输出:
*Hello my name** *******is******* ****John Doe****