gpt4 book ai didi

c++ - Boost String Replace 不会用字符串替换换行符

转载 作者:太空狗 更新时间:2023-10-29 23:45:33 25 4
gpt4 key购买 nike

我正在为我的 libspellcheck 拼写检查库创建一个函数来检查文件的拼写。它的功能是读取文本文件并将其内容发送到拼写检查功能。为了让拼写检查功能正确处理文本,所有换行符都必须替换为空格。我决定为此使用 boost。这是我的功能:

spelling check_spelling_file(char *filename, char *dict,  string sepChar)
{

string line;
string fileContents = "";
ifstream fileCheck (filename);
if (fileCheck.is_open())
{
while (fileCheck.good())
{
getline (fileCheck,line);
fileContents = fileContents + line;
}

fileCheck.close();
}
else
{
throw 1;
}

boost::replace_all(fileContents, "\r\n", " ");
boost::replace_all(fileContents, "\n", " ");

cout << fileContents;

spelling s;
s = check_spelling_string(dict, fileContents, sepChar);

return s;
}

编译库后,我创建了一个带有示例文件的测试应用程序。

测试应用代码:

#include "spellcheck.h"

using namespace std;

int main(void)
{
spelling s;
s = check_spelling_file("test", "english.dict", "\n");

cout << "Misspelled words:" << endl << endl;
cout << s.badList;
cout << endl;

return 0;
}

测试文件:

This is a tst of the new featurs in this library.
I wonder, iz this spelled correcty.

输出是:

This is a tst of the new featurs in this library.I wonder, iz this spelled correcty.Misspelled words:

This
a
tst
featurs
libraryI
iz
correcty

如您所见,换行符没有被替换。我做错了什么?

最佳答案

std::getline 在从流中提取时不读取换行符,因此它们更新写入 fileContents

此外,您不需要搜索和替换 "\r\n",流将其抽象化并将它们转换为 '\n'

关于c++ - Boost String Replace 不会用字符串替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024510/

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