提升字符串替换不会用字符串替换换行符

Boost String Replace Doesn't Replace Newline With String

本文关键字:字符串 替换 换行符      更新时间:2023-10-16

我正在为我的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, "rn", " ");
    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中写得较新。

此外,您不需要搜索和替换"rn",流将其抽象并翻译为'n'

std::getline()从流中提取换行符,但不包括在返回的std::string中,因此fileContents中没有换行符需要替换。

此外,立即检查输入操作的结果(请参阅循环条件内的iostream::eof为什么被认为是错误的?):

while (getline (fileCheck,line))
{
    fileContents += line;
}

或者,要将文件的内容读取到std::string中,请参阅在C++中将整个文件读取到std::字符串中的最佳方法是什么?然后应用CCD_ 9。