gpt4 book ai didi

c++ - 控制台输出线的宽度限制

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:48 25 4
gpt4 key购买 nike

Class 向控制台打印一个字符串。如何使输出行的宽度等于 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;
};

我有一个想法但是这里console中的字被截断了,所以需要调到下一行进行宽度对齐

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;
}
}

最佳答案

这是适合我的答案

#include <string>
#include <iostream>
#include <iomanip>

class StringProcessing
{
public:
StringProcessing() : characterWidth(40),
textToBeFormatted("NULL") {}

inline void 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 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()
{
const std::string& s = textToBeFormatted;
const int& width = characterWidth;
for (int current = 0; current < s.length();)
{
if (s.length() < width)
{
output(s);
break;
}
if (s.length() - current < width)
{
output(s.substr(current));
break;
}
std::string substr = s.substr(current, width);
current += width;
size_t space = substr.rfind(' ');
if (space != std::string::npos && (substr[width - 1] != ' ' &&
(s.length() > current && s[current] != ' ')))
{
current -= width - space - 1;
substr = substr.substr(0, space + 1);
}
output(substr);
}
}
private:
inline void output(const std::string& s)
{
std::cout << setfill(' ') << std::right << std::setw(characterWidth) << s << std::endl;
}
int characterWidth;
std::string textToBeFormatted;
};

关于c++ - 控制台输出线的宽度限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21486958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com