I was practicing C program that i read from The C ANSI Programming Language Second Edition
I learn about getchar() function.And the book say that getchar() read the character from stdin until newline character or EOF has been reached.And in the book i try to rewrite the program to count character using getchar() function.The code is fine when compiling. The problem is the code unable to display the long of character.
Here is the code:
#include <stdio.h>
int main (void){
long nc;
nc=0;
while(getchar()!=EOF)
nc++;
printf("%ld\n",nc);
return 0;
}
But when i change the EOF to newline character \n the code working as i expected but only
display the long of character only one line. After that the code terminate.
My question is what is EOF exactly is and what is the difference between EOF and newline character.
Is there other way to fix this program?
getchar() returns EOF when you get to the end of the file. It returns \n when you get to the end of the line. This is why your loop finishes when it gets to the end of the line if you replace EOF with \n.
EOF means End of File and you get that when your getting to the end of a file with getchar(). You get \n when you get to the end of a line.
When you now want it, so that it prints the text again use this:
#include <stdio.h>
int main(void) {
int c, nc = 0;
while ((c = getchar()) != '\n') {
nc++;
putchar(c);
}
printf("%d\n",nc);
return 0;
}
EOF is the end of file. It does not mean the end of your "long of character". If you just type many characters occupying several lines on the command line screen, the program still does not get the EOF unless you type Ctrl+D simulating the end of file. When you change EOF to "\n", the program requires the end of line. And when you finish the first line, the program get the end of the first line and run. That is why the code works as you expected but only display the long of character only one line.
Related
I don't understand how this code can display a string by using just getchar, I know that it has something to do with buffers, but I don't understand it.
#include <stdio.h>
int main() {
int c;
puts("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c = getchar();
putchar(c);
} while (c != '.');
return 0;
}
Simply reads each character one by one with getchar and prints immediately with putchar. When encounters a dot (.), prints it and then terminates. Hence it doesn't store more than a single character at a time.
do-while loop
Executes a statement repeatedly, until the value of expression becomes false. The test takes place after each iteration.
getchar
Reads the next character from stdin.
Equivalent to getc(stdin).
putchar
Writes a character ch to stdout. Internally, the character is converted to unsigned char just before being written.
Equivalent to putc(ch, stdout).
Code may look like I/O happens immediately, but certainly both stdin and stdout are buffered by lines.
The first getchar() likely does not return until a line (characters up to and including a '\n') of input happens. Then the first call gets the first characters, 2nd calls gets the second, etc.
Similar for output. Output is not "printed" until a '\n' is sent.
To see output without waiting for a putchar('\n'), follow the putchar() with fflush(stdout);.
To read one character immediately with getchar() takes more work. No answer for that at this time.
I am confused by a program mentioned in K&R that uses getchar(). It gives the same output as the input string:
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.
There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.
If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c
getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.
According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar and buffered stdin :
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.
I am confused by a program mentioned in K&R that uses getchar(). It gives the same output as the input string:
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.
There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.
If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c
getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.
According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar and buffered stdin :
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.
I'm working through "The C Programming Language" by K&R and example 1.5 has stumped me:
#include <stdio.h>
/* copy input to output; 1st version */
int main(int argc, char *argv[])
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
I understand that 'getchar()' takes a character for 'putchar()' to display. However, when I run the program in terminal, why is it that I can pass an entire line of characters for 'putchar()' to display?
Because your terminal is line-buffered. getchar() and putchar() still only work on single characters but the terminal waits with submitting the characters to the program until you've entered a whole line. Then getchar() gets the character from that buffer one-by-one and putchar() displays them one-by-one.
Addition: that the terminal is line-buffered means that it submits input to the program when a newline character is encountered. It is usually more efficient to submit blocks of data instead of one character at a time. It also offers the user a chance to edit the line before pressing enter.
Note: Line buffering can be turned off by disabling canonical mode for the terminal and calling setbuf with NULL on stdin.
Yeah you can actually write whatever you want as long as it's not an EOF char, the keyboard is a special I/O device, it works directly through the BIOS and the characters typed on the keyboard are directly inserted in a buffer this buffer is, in your case read by the primitive getchar(), when typing a sentence you are pushing data to the buffer, and the getchar() function is in an infinite loop, this is why this works.
You can ask me more questions if you want more details about how the IO device work.
Cheers.
Consider the following program,
This program gets the input (getchar runs) till we enter '$' character and prints the output.
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != '$')
putchar(c);
return 0;
}
If we enter input as abcd$$$$$$[Enter], it stores the input in buffer till the last $ symbol. After we pressed enter, the program (while loop) starts to run and getchar function receives one character at a time and prints it, from 'a' till first '$' .
And the program won't end till we press '$' in the input.
I am confused by a program mentioned in K&R that uses getchar(). It gives the same output as the input string:
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.
There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.
If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c
getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.
According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar and buffered stdin :
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.