Reputation: 558
I am creating a function for my libspellcheck spell checking library that checks the spelling of a file. It's function is to read a text file and send its contents to the spell checking function. In order to have the spellchecking function process the text correctly, all newlines must be replaced with a space. I decided to use boost for this. Here is my function:
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;
}
After compiling the library, I created a test application, with a sample file.
Test application code:
#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;
}
Test file:
This is a tst of the new featurs in this library.
I wonder, iz this spelled correcty.
The output is:
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
As you can see, the newlines are not being replaced. What am I doing wrong?
Upvotes: 2
Views: 1239
Reputation: 122001
std::getline()
extracts the newline character from the stream but does not include it in the returned std::string
, so there is no newline characters in fileContents
to be replaced.
Also, check result of input operations immediately (see Why is iostream::eof inside a loop condition considered wrong?):
while (getline (fileCheck,line))
{
fileContents += line;
}
Alternatively, to read the contents of the file into a std::string
, see What is the best way to read an entire file into a std::string in C++? and then apply the boost::replace_all()
.
Upvotes: 4
Reputation: 55415
std::getline
doesn't read newline characters when it extracts from the stream and so they're newer written in fileContents
.
Also, you don't need to search and replace "\r\n"
, streams abstract this away and translate them to '\n'
.
Upvotes: 5