gpt4 book ai didi

c++ - 修复/改进自动换行功能

转载 作者:行者123 更新时间:2023-11-28 08:21:06 32 4
gpt4 key购买 nike

我有一个简单的自动换行函数,它接受一个长字符串作为输入,然后将该字符串分成更小的字符串,并将它们添加到一个数组中,以便稍后输出。现在最后一两个字没有输出。这是主要问题。但是,我还想改进功能。我知道这有点乱。我想知道是否有更好的方法来解决这个问题。我认为数组是不必要的,但我不知道该怎么做。在数组中填满所有较小的字符串后,我将它们输出到一个文本文件中。任何建议将不胜感激。

这是自动换行功能:

void WordWrap(string inputString, string formatedAr[], const int SIZE)
{
unsigned int index;
unsigned int word;
unsigned int max = 65;
string outWord;
string outLine;

outWord = "";
outLine = "";
word = 0;

for(int i = 0; i < SIZE; i++)
{
formatedAr[i] = "";
}

for(index = 0; index <= inputString.length(); index++)
{
if(inputString[index] != ' ')
{
outWord += inputString[index];
}
else
{
if(outLine.length() + outWord.length() > max)
{
formatedAr[word] = outLine;
word++;
outLine.clear();
}
outLine += outWord + " ";
outWord.clear();
}
}
formatedAr[word] = outLine;
}

这是我调用函数并输出数组的地方:

WordWrap(dvdPtr -> synopsis, formatedAr, SIZE);

index = 0;

while(index < SIZE && formatedAr[index] != "")
{
outFile << formatedAr[index] << endl;
index++;
}

最佳答案

这是一个示例代码。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

void WordWrap(const string& inputString, vector<string>& outputString, unsigned int lineLength)
{
istringstream iss(inputString);

string line;

do
{
string word;
iss >> word;

if (line.length() + word.length() > lineLength)
{
outputString.push_back(line);
line.clear();
}
line += word + " ";

}while (iss);

if (!line.empty())
{
outputString.push_back(line);
}
}

/*
A simple test:

Input string: "aaa bbb ccccccc dddd d111111111111111 33333 4444444444 222222222 ajdkjklad 341343"

Length per line: 20

Output lines of strings:

Line 1: aaa bbb ccccccc dddd
Line 2: d111111111111111
Line 3: 33333 4444444444
Line 4: 222222222 ajdkjklad
*/

关于c++ - 修复/改进自动换行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5815227/

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