4

This is making no sense to me, but hopefully one of you understand why it's doing this.

I have an assignment that requires three characters be read with getchar() as the three integers next to one another are relevant to each other, so I set up a loop structured as such:

int c1, c2, c3 = 0;

while(c3 != EOF) {
    c1 = getchar();
    c2 = getchar();
    c3 = getchar();
    ... do something with them...
}

The problem is that if the amount of characters is not divisible by three, the last iteration is not executed. So, if the characters "Abcd" were entered, it would do the first iteration on Abc, but the second iteration wouldn't do anything with D. Same for "Abcde", but Abcdef would work.

This is a homework assignment so don't solve the problem for me, but is this something weird about getchar that it just terminates the loop if that many characters aren't found?

Macmade
  • 52,708
  • 13
  • 106
  • 123
user1661781
  • 327
  • 2
  • 16

3 Answers3

1

getchar is a blocking call, so it won't return until it reads a character or EOF is encountered.

So, either check to see if any of c1, c2 or c3 is a newline after the corresponding getchar call (to see if the line of input has ended), or press Ctrl+D (*nix, OS X) or Ctrl+Z (Windows) to signal the end-of-file (EOF). After EOF, getchar will always return immediately with EOF.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Break down your problem into states. Define what should be done on different input in different states. Translate to code.

In your case, you need to figure out when input of an unwanted length will affect you and how to handle it. Reading in triplets works fine, but for every character you get, you need to see if you should raise an error or treat it in a special way.

Try to run the strings "", "a", "ab", "abc" and "abcd" through your described states and see if you can handle them all in a sane way. When this works, writing the code should not be a problem.

HonkyTonk
  • 1,961
  • 11
  • 11
0

An easy way to simulate a short file is to use echo and pipe to your program:

echo ABC | ./program_name

This way, you can test with different strings on the command line. The output of echo will be piped to the stdin of your program. The stdin in your program will be closed at end of string. This avoids the EOF problem that causes getchar to block when you test using the keyboard directly (besides the terminal line/char input method).

Another gotcha is that EOF is an int constant. So check if your code don't convert c1, c2, c3 to char later on. It is ok, but if you convert them to char, you can't compare anymore with EOF.

nmenezes
  • 910
  • 6
  • 12