提升字符串替换不会用字符串替换换行符
Boost String Replace Doesn't Replace Newline With String
我正在为我的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。
相关文章:
- 如何使用regex_replace将子字符串替换为字符串中的另一个子字符串,同时保持整个文本完整?
- 使用C++将一个字符串替换为另一个字符串
- 简单的字符串替换给出错误,尽管参数正确
- UnicodeString 将一个子字符串替换为另一个子字符串
- C++字符串.替换生成"No matching function for call"错误
- std::字符串替换不保留结尾?
- GCC Bug,使用尖括号通过宏包含标头时"linux"路径中的字符串"<>"替换为 "1"
- 字符串替换问题
- 将带双引号的字符串替换为带双引号的字符串
- 如何在C++中将字符串替换为"Match case"和"Match whole word"
- 字符串替换和奇怪的字符
- C++中的字符串反转不将旧字符串替换为新字符串
- 用c++字符串替换snprintf
- 字符串::替换在有效的迭代器上抛出 std::out_of_range
- 简单的标准::字符串替换在C++
- C++字符串替换函数无限循环
- 分析字符串替换内存泄漏
- C++:-用另一个字符串替换一段字符串
- 提升字符串替换不会用字符串替换换行符
- C++中任意长度字符串的字符串替换