-1

I wrote a function that spellchecks a line read from a file which takes in a file stream and a delimiter as parameters. My problem is that the function requires a delimiter, but when reading in the last line, I haven't got one. I would use the last character of the file, but I need that last character for spellcheck purposes.

Is there any way to use the EOF macro as a delimiter?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 4
    Please post your code, preferably a [mcve]. – R Sahu Feb 20 '18 at 23:07
  • 2
    What do you mean by the function "requires a delimiter"? This is C++, so presumably you're using `std::string`, so the end of the string serves very well as an "end" indicator. – Greg Hewgill Feb 20 '18 at 23:08
  • So, you reinvented [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) with some added spell checking? If so, I would strive to mimic it's behavior if that is the case. When the end-of-stream is encountered before the delimiter, whatever was consumed is "the line". I.e. the final delimiter is optional. The case where the final delimiter is present, *then* end-of-stream is encountered is usually more problematic than the case you're citing. – WhozCraig Feb 20 '18 at 23:08
  • Answer: No. There is a fault in the design, namely one function is supposed to handle three concerns: reading the file, parsing the stream, and spell-checking. – Jive Dadson Feb 20 '18 at 23:09
  • The API you use to read from the file will have a way for you to check whether you have reached the end of the file. But you have not told which API you are using, or how you have structured your code - if you do so, it will be easy to help you. – nos Feb 20 '18 at 23:09
  • 1
    I would say no. Functions that return an EOF value are returning an `int` type, not `char`. – Thomas Matthews Feb 20 '18 at 23:10
  • 1
    Your problem is that your undisclosed function isn't written correctly. You don't need to further complicate matters by adding a so-called 'delimiter for EOF'. You just need to fix your code. There are plenty of existing ways to read lines correctly, including unterminated final ones. No need to reinvent that wheel. – user207421 Feb 20 '18 at 23:49
  • Why don't you just append your usual delimiter to the end of the data read in, if the EOF condition occurs and the last character wasn't that delimiter already? – M.M Feb 21 '18 at 00:05

1 Answers1

0

Typically, you would let the stream tell you when it has received an EOF signal in whatever platform-dependent way is appropriate (be that the end of a file, or Ctrl+D on a Linux terminal emulator).

So, stop reading when you hit your custom delimiter, or when an attempt to read from the stream sets the stream's EOF bit. You ought to be checking the stream's state anyway — what if there's an error? You'll be looping forever at the moment.

That's how std::getline and co do it, anyway.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055