【发布时间】:2014-02-24 13:18:14
【问题描述】:
类将字符串打印到控制台。 如何使输出行的宽度等于characterWidth = 40, 即 40 个字符后转移到新行?
#include <string>
#include <iostream>
class StringProcessing {
public:
StringProcessing() : characterWidth(40),
textToBeFormatted("NULL") {}
inline void StringProcessing::initString() {
textToBeFormatted =
"text some text some text some text some text some text"
"text some text some text some text some text some text"
"text some text some text some text some text"
"text some text some text some text some text some text"
"text some text some text some text some text some text";
}
inline void displayString()
{ std::cout << textToBeFormatted << std::endl; }
private:
int characterWidth;
std::string textToBeFormatted;
};
我有一个想法但是这里控制台中的单词被截断了,所以需要转移到下一行并进行宽度对齐
inline void displayString()
{
const std::string& s = textToBeFormatted;
for (int i = 0; i < s.length() / 40 + (bool)(s.length() % 40); ++i)
{
std::cout << std::left
<< std::setfill(' ')
<< std::setw(40)
<< s.substr(i * 40, 40)
<< std::endl;
}
}
【问题讨论】:
-
还有什么问题?您是否试图证明文本的合理性?它让我想起了动态规划,这是一种“书例”:stackoverflow.com/q/18200593/1168156
-
谢谢,我想这是我需要的
标签: c++