Reading three characters per iteration of a loop in C?

That doesn't make any sense to me, but hopefully one of you understands why he does it.

I have an assignment that requires three characters to be read with getchar (), since the three integers next to each other are related 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 number of characters is not divided by three, the last iteration is not performed. So, if the characters "Abcd" were entered, it would do the first iteration on Abc, but the second iteration would not do anything with D. The same thing for "Abcde", but Abcdef would work.

This is homework, so don’t solve the problem for me, but is it something weird about getchar that it just ends the loop if a lot of characters are not found?

+4
source share
3 answers

getchar is a blocking call, so it does not return until it reads a character or EOF.

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

+1
source

Divide your problem into states. Define what needs to be done on different inputs in different states. Translate to code.

In your case, you need to find out when entering an unwanted length will affect you and how to deal with it. Reading in triplets works great, but for each character you get, you need to see if you should raise a mistake or treat it in a special way.

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

0
source

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

 echo ABC | ./program_name 

This way you can test using different lines on the command line. The echo output will be sent to the channel in the stdin of your program. Stdin in your program will close at the end of the line. This avoids the EOF problem, which causes getchar to block during direct testing using the keyboard (in addition to the terminal input method / char).

Another problem is that EOF is an int constant. So check if your code will not convert c1, c2, c3 to char later. This is fine, but if you convert them to char, you can no longer compare with EOF.

0
source

Source: https://habr.com/ru/post/1434729/


All Articles