在输出输入文本时对齐输入的文本

aligning inputed text when it is outputted?

本文关键字:输入 文本 对齐 输出      更新时间:2023-10-16

我正在开发一个程序,当用户输入文本时,他们可以指定如何对齐输出。因此,用户将在那里输入文本,然后询问他们想要的文本的对齐方式和宽度(中心,左侧,右侧,然后是宽度(。您将如何获得宽度和对齐方式的代码?到目前为止,我只有获取用户输入的代码,但我不确定如何让程序让用户输入他们的条件(左、右、中心和宽度(,然后对齐用户给出的输入。这是我到目前为止得到的。

#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:nn";
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: nn";
for ( auto &s : output )
    std::cout << s << "n";
return 0;
}

测试用例(实际输出有空格,而不是*(:

输入(对齐=右,宽度=10(:

Hello my
name is
John Doe

输出:

**Hello my
***name is
**John Doe

输入(对齐=中心,宽度=16(:

Hello my name
is
John Doe

输出:

*Hello my name**
*******is*******
****John Doe****