0

The expected input to my program for my assignment is something like ./program "hello" < helloworld.txt. The trouble with this however is that I must analyse every line that is in the program, so I have used the guard for the end of a line as:

while((c = getchar()) != EOF) {
    if (c == '\n') {
    /*stuff will be done*/

However, my problem with this is that if the helloworld.txt file contains:

hello
world

It will only read the first line(up to the second last line if there were to be more lines).

For this to be fixed, I have to strictly make a new line such that helloworld.txt looks something like:

hello
world
//

Is there another way around this?

Laefica
  • 489
  • 1
  • 5
  • 13
  • 3
    Did your original file have a newline at the end of `world`? Some editors add those, some don't. Perhaps "do stuff" on EOF as well as `\n`? – DevSolar Sep 18 '15 at 12:52
  • @DevSolar I'm just assuming the worst in which the person marking it uses a test file that does not have a new line. – Laefica Sep 18 '15 at 12:53
  • But in that case you have read characters *but not done "stuff"* when you encounter EOF (and presumably exit). That's why your last line doesn't show up. – DevSolar Sep 18 '15 at 12:54

2 Answers2

5

Fix your algorithm. Instead of:

while((c = getchar()) != EOF) {
    if (c == '\n') {
        /* stuff will be done */
    } else {
        /* buffer the c character */
    }
}

Do:

do {
    c = getchar();
    if (c == '\n' || c == EOF) {
        /* do stuff with the buffered line */
        /* clear the buffered line */
    } else {
        /* add the c character to the buffered line */
    }
} while (c != EOF);

But please note that you shouldn't use the value of the c variable if it is EOF.

3

You need to re-structure your program so it can "do stuff" on EOF, if it has read any characters since the previous linefeed. That way, a non-terminated final line will still be processed.

unwind
  • 391,730
  • 64
  • 469
  • 606