Reputation: 27
I wrote a program to read the first character in a line by using the C here is my code:
#include <stdio.h>
int main(void) {
char ch;
printf("Please type text for test(# for terminate)\n");
while((ch = getchar()) != '#') {
printf("\n %c", ch);
while (getchar() != '\n')
continue;
printf("\nPlease type text for test(# for terminate)\n");
}
return 0;
}
My question is when I changed the second while into if, the program would print all the character in odd position(the first,the third,the fifth....) instead of only the first character. I don't know why
Upvotes: 0
Views: 1963
Reputation: 498
Every time getchar() is called, it's eating a single character from stdin. You have two calls to getchar() in your above code, and they're alternating (the call in your while() is made, then the call in your if() is made). However, only the first call ever stores the returned character and prints it, the second call just eats the character and does nothing with it. An example:
Input: "Example"
See how that works?
Upvotes: 3
Reputation: 228
The second WHILE loop will execute till '\n' character is seen. Beacuse when CONTINUE is called, control goes to second WHILE loop itself. So it prints only first character.
But if second WHILE loop is replaced with IF loop, then when CONTINUE is called, the control goes to the first WHILE loop. Here also a getchar() is called. So it keeps printing characters in odd positions.
Upvotes: 0
Reputation: 1
When you have a second while, that's where your continue takes you. But when you have an if, the continue takes you to the first while. You then have 2 calls to getchar(), resulting in odd positions being read.
You should try debugging this step-by-step to understand better.
Upvotes: 0
Reputation: 5110
It will ignore just every other letter. Now, with second while
, you are printing first letter and ignoring rest of the letters from the line. Changing it to the if
you reading every odd positioned letter.
Keep id mind while
is looping construct while if
is conditional construct. Anything which is inside if
will be executed only once.
Upvotes: 0
Reputation: 28806
The second while
loop reads all characters after the first character until a newline is pressed. In other words, it reads the rest of the line and ignores it.
If you change the while
to if
, it only reads one character and then goes on with the outer loop. That explains why you get all these characters on different positions.
Upvotes: 0