-
getchar Query
Hi All,
am new to C programming. I am following this online tutorial,
http://publications.gbdirect.co.uk/c..._programs.html
and tried this example,
Code:
#include <stdio>
#include <stdlib.h>
main(){
int ch;
ch = getchar();
while(ch != 'a'){
if(ch != '\n')
printf("ch was %c, value %d\n", ch, ch);
ch = getchar();
}
exit(EXIT_SUCCESS);
}
and got this output,
:~/scripts$ ./char
k
char is k, value 107
char is k, value 107
I do not understand why it prints the result twice, and what is the reason for the 2nd ch = getchar() after the printf statement. Could anyone comment on this example code? Cheers.
coolboarerguy
-
You need to include <stdio.h>, not <stdio>, and you need an "int" in front of main.
The second getchar just keeps getting the next character from the input stream. (Since it's inside a loop, it may happen a bunch of times.)
The only way to get two statements like that is to type k twice. Even if a control character other than \n got in there, like \r or something, it would still print that instead of k.
-
Hi All,
sorry, that was copy/pasted from the site, whilst my code had <stdio.h> in it, as I did it from my own memory of the example code. I did pick up on the need for int instead of char. I still don't understand why it prints it twice. Cheers.
coolboarderguy
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int ch;
ch = getchar();
while(ch != 'a'){
if(ch != '\n')
printf("char is %c, value %d\n", ch, ch);
getchar();
}
exit(EXIT_SUCCESS);
}
-
Because you lost the "ch =" in front of the getchar(); the second time.
-
DOH!!! Thanx.
coolboarderguy