在输出输入文本时对齐输入的文本
aligning inputed text when it is outputted?
我正在开发一个程序,当用户输入文本时,他们可以指定如何对齐输出。因此,用户将在那里输入文本,然后询问他们想要的文本的对齐方式和宽度(中心,左侧,右侧,然后是宽度(。您将如何获得宽度和对齐方式的代码?到目前为止,我只有获取用户输入的代码,但我不确定如何让程序让用户输入他们的条件(左、右、中心和宽度(,然后对齐用户给出的输入。这是我到目前为止得到的。
#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****
相关文章:
- 如何使输入文本文件成为构造函数参数?c++
- 用C++计算输入文本的新行数
- 是否有任何方法可以在用户输入文本时读取字符
- C++程序 - 输入文本流
- 在输出输入文本时对齐输入的文本
- 根据输入文本对单词进行排序,具体取决于重复多少次
- 查找字符在标准输入文本中出现的次数
- 将不同长度的cstrings从输入文本文件读取到链接列表中
- C++交叉编译不处理换行输入文本文件
- 要求用户在C++中创建文本文件时输入文本文件(ASCII)名称
- 如何使用字符串操作来获取输入文本文件的某些部分
- 如何使用 WxWebView 在网页表单字段中输入文本
- 为什么 fstream::tellg() 返回值会因输入文本文件中的换行符数而增大,当文件针对 Windows (r
- 匹配输入文本中的平衡大括号和嵌套大括号
- 使用 OpenCV 显示图像,并在C++中的特定点上输入文本
- (Qt)可编辑的Q组合框:don't在输入文本时关闭弹出窗口
- 如何从文件的输入文本中消除字符/整数
- 大型输入文本文件,每行有两个数字,如何更快地输入
- 重新输入文本到字符串
- 我如何运行GDB,在命令行中输入文本并查看可执行文件如何处理这些条目