can some1 explain how this code works...
Code:#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
Printable View
can some1 explain how this code works...
Code:#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
I'm sure the vast majority of us could explain it, but we're not new students learning it. Have you tried the program? Just enter some letters and numbers and either press ctrl+z (Windows) or ctrl+d (Linux), to end the program. It works with just one character at a time, but changes the character you enter, into an int (int's are bigger than char's you see). Only an int can be used to detect the EOF (end of file) integer value.
And welcome to the forum!
Why don't you explain your understanding of how it works? We can then correct any misunderstandings you might have.
If someone explains the code to you, but fails to address something that is blocking your understanding, then you would be even more confused than you are now.
i have tried the program...
it accepts wat ever i enter in a single line not just one character
You use a file - stdin, which C opens for you, every time it's running. (along with four others).
It works with int's because it was made so it detects EOF, and it works with every char, individually, but in a loop, see? It's like keyboarding - you press one key at a time, but your line of text may be quite long.
getchar() pauses the program, or removes the last char from the input stream of the keyboard buffer, if present. Terminal windows (not run from inside an ide), immediately close upon completion of the running program - so without a pause, you couldn't see what had happened, since the terminal window (aka command window) just closed up.