Boost字符串替换不会用字符串替换换行符

Igo*_*gor 2 c++ string boost

我正在为我的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;
}
Run Code Online (Sandbox Code Playgroud)

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

测试应用代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

测试文件:

This is a tst of the new featurs in this library.
I wonder, iz this spelled correcty.
Run Code Online (Sandbox Code Playgroud)

输出是:

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
Run Code Online (Sandbox Code Playgroud)

如您所见,新行不会被替换.我究竟做错了什么?

jro*_*rok 5

std::getline从流中提取时不会读取换行符,因此它们是新写入的fileContents.

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