如何使用新式C++在控制台中打印"justified"文本
How to print "justified" text in the console using modern C++
如何格式化文本"对齐",使其在给定宽度的左右两侧对齐?
int main()
{
printJustified("A long text with many words. "
"A long text with many words. "
"A long text with many words. "
"A long text with many words. "
"A long text with many words.");
}
预期输出:
A long text with many words. A long text with
many words. A long text with many words. A
long text with many words.
如何解决此问题的一个简单示例是:
#include <iostream>
#include <sstream>
#include <list>
const int pageWidth = 78;
typedef std::list<std::string> WordList;
WordList splitTextIntoWords( const std::string &text )
{
WordList words;
std::istringstream in(text);
std::copy(std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>(),
std::back_inserter(words));
return words;
}
void justifyLine( std::string line )
{
size_t pos = line.find_first_of(' ');
if (pos != std::string::npos) {
while (line.size() < pageWidth) {
pos = line.find_first_not_of(' ', pos);
line.insert(pos, " ");
pos = line.find_first_of(' ', pos+1);
if (pos == std::string::npos) {
pos = line.find_first_of(' ');
}
}
}
std::cout << line << std::endl;
}
void justifyText( const std::string &text )
{
WordList words = splitTextIntoWords(text);
std::string line;
for (const std::string& word : words) {
if (line.size() + word.size() + 1 > pageWidth) { // next word doesn't fit into the line.
justifyLine(line);
line.clear();
line = word;
} else {
if (!line.empty()) {
line.append(" ");
}
line.append(word);
}
}
std::cout << line << std::endl;
}
int main()
{
justifyText("This small code sample will format a paragraph which "
"is passed to the justify text function to fill the "
"selected page with and insert breaks where necessary. "
"It is working like the justify formatting in text "
"processors.");
return 0;
}
它是这样工作的:
- 首先把课文分成几个单词
- 单词被添加到行中,直到该行不能容纳更多单词为止
- 对于每一行,在单词之间添加空格,直到该行与请求的宽度相匹配
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用新式C++在控制台中打印"justified"文本