This question already has answers here:
What is EOF in the C programming language?
(10 answers)
Closed 5 years ago.
I am new to coding and I am learning through a book called "The C Programming Language - 2nd Edition - Ritchie Kernighan" and there is this code:
#include<stdio.h>
#include<stdlib.h>
int main(){
int c,nl;
nl =0;
while((c=getchar())!=EOF)
if(c == '\n')
++nl;
printf("%d\n",nl);
return 0;
}
After typing the code in CodeBlocks I run it and when I type in a word and press enter nothing happens. The word is not being counted and printed. I am new to all of this but if anyone has an idea feel free to share it. Thank you very much !
The issue is that you never read the EOF (End Of File); this is the end of the input data coming from the console (where you type).
Everything you type is either a letter, digit, special character, or newline, but never EOF.
To generate an EOF you need to enter a special control-key combination. On Windows this is Ctrl+Z and on UNIX/Linux/macOS this is Ctrl+D.
The book you're reading is great and written by the two creators of C. It one of my first programming books and I still have it; all worn-out.
Small piece of advice: Always put your code blocks inside { } to avoid mistakes and create more visual clarity, use spaces consistently, and add empty lines. Your code would look like this:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
{
if (c == '\n')
{
++nl;
}
}
printf("%d\n", nl);
return 0;
}
Why should it stop? Your expectations are wrong. getchar() will go on getting characters until it encounters EOF.
How to pass that to getchar?
For Windows Ctrl+Z will do the trick. And then press Enter.
For Unix or Linux system it would be Ctrl+D
Responsive output before entering EOF
To get a more responsive output you can add this line, that will tell you the cumulative sum of \n found.
if(c == '\n'){
++nl;
printf("Till now %d newline found",nl);
fflush(stdout);
}
Further Explanation of the added code
The code segment provided above will provide you some output when you press enter. But the thing is until you enter EOF it will keep on waiting for more and more input. That's what also happened in the first case. So you have to press Ctrl+Z and press Enter. That will break the loop. And you will see the final output - the number of line count.
Related
I am doing Kernighan/Ritchie ANSI C Second Edition exercises in the first chapter. Problem is, the book didn't teach you yet about argv/argc or fopen, yet it uses such a structure where if you just run your program and give input at runtime, you will get into an infinite repetition of the test (c = getchar()) != EOF because getchar() at runtime will prompt the user for input as soon stdin is empty, and when the user gives input, the input will process, and getchar() will prompt for another input. EOF will literally never get encountered.
My mentors told me that you can input an EOF with ctrl+d, but that is obviously a hack and not intended.
Another solution they gave me is a.out <<< "some string" which actually works and does have EOF, but now I am at a point where I have to have an input of multiple lines, and I have no idea how to input lines like this, and frankly I heard that <<< didn't even exist in 1989.
Here is a code example of the type of problem:
#include <stdio.h>
/* count characters in input; 1st version */
int main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
So how did programmers feed input in this kind of program back in the day? Mind you, you are only allowed to use the things the book taught you until now (which is literally nothing about input)
This question already has answers here:
Problem with example 1.5.2 in K&R book on C
(5 answers)
Closed 2 years ago.
i was practicing the line counting program. I'm a little bit confused how should i be giving input to this program. I tried typing random sentences including '\n' - the new line element inside my program. But no matter what output i give , the output is still blank and asking me to keep typing. I've went through Internet for a while , and i couldn't figure out where i failed. Can you help me please. I was going to skip this lesson and come back again. But the later lessons of the text book depends on this topic . Thanks
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
So, the output is still blank because your program's stuck at a while loop, since the code beneath it is not between curly brackets ({}), that way, your program is asking for input characters indefinitely with no outputs as a result.
Also, I was a little confused by your code since I didn't how to get to EOF through stdin without using file redirection. And by searching through Stack Overflow I've found out that you need to type Ctrl+D, at UNIX-based systems, or Ctrl+Z, on Windows, in order to use EOF through console typing.
(End of File(EOF) of Standard input stream (stdin))
By the way, I've modified your code, I just don't know if that was exactly what you were trying to do:
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)//EOF can be reached by stdin when pressing Ctrl+D
{
if (c == '\n')
{
++nl;
}
}
printf("Number of lines: %d\n", nl);
}
Good coding!
I am studying C from The C Programming Language. I have tried to make the following code work:
#include <stdio.h>
int main() {
int char_count = 0;
while (getchar() != EOF)
++char_count;
printf("Number of chars are %ld ", char_count);
return 0;
}
I build and run the code. Then, I enter a random word and press enter. I expect to see a number in the next line, but what happens is that cursor moves to the next line. When I enter a new word same thing happens. What am I missing?
Edit: I expect getchar() to return EOF when the program finishes getting the characters of the first word.
When you are pressing enter/return you are generating \n or \r\n based on the whether you are using unix/osx or windows. You are not generation EOF character.
To generate EOF character you need to press ^D on unix/osx or ^Z on windows.
Inputting the EOF character into the command prompt is always tricky. Doing what #Sarvex recommended will do the trick, by using Ctrl+Z on Windows or Ctrl+D on Unix.
One other interesting thing that you can do without making any changes to your code is instead of having your program accept input from the command prompt, you can redirect input to your program from a text file.
If you had a text file named, "data.txt" with the following text in it:
Hello World. How are you doing?
And the name of your program, after compiling the code was charCount. You could do the following:
The output I received was, Number of chars are 31.
If you change the EOF to \n character, it will do the work after pressing the enter key:
int c = 0;
while (((c = getchar()) != '\n') && (c != EOF))
++char_count;
P.S: Improved Using #David Bowling suggestion.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am learning C language from a book called "The C Programming Language" by Brian Kernighan & Dennis Ritchie and have been stuck at its basic lesson of line counting program. The program runs but it does not give an output of how many lines were inputed.
Have given the program code below, please help on the same.
#include <stdio.h>
void main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF )
if (c == '\n')
++nl;
printf("%d \n", nl);
return 0;
}
The code should read the input and then output how many lines of text were given. How should this be changed to make it work?
Your program works fine. However, I would prefix main with the int type to keep the compiler quiet. It should look like this:
int main(void)
When you call it, what I did was this:
$$$ ->./test6 < test4.c
19
$$$ ->wc test4.c
19 48 379 test4.c
$$$ ->
The getchar function is the same thing as getc(stdin), so when you run your program, it takes it's input from stdin (keyboard) or a file redirected to stdin.
EDIT: As someone pointed out, if the last line doesn't have a \n terminator, that line will not be counted. So I rewrote your code to account for this:
#include <stdio.h>
int main(void)
{
int c; /* Character */
int cp; /* Previous Character */
int n; /* Number of lines */
n = 0;
c = 0;
while (1)
{
cp = c;
c = getchar();
if (c == '\n')
{
n++;
continue;
}
if (c == EOF && cp == '\n') break;
if (c == EOF)
{
n++;
break;
}
}
printf("%d \n", n);
return 0;
}
As you can see in the code, I used fall-though logic to either continue the loop or to break out of it. Now I tested this code using clang on FreeBSD and it works properly.
The logic of this program is as follows:
Save current character as the previous character.
Get the next character and make it the current character.
Check the current character to see if it's a newline character.
If it is, then we increment the line counter and restart the loop.
Check the current character to see if it's EOF and the previous character to see if it's the newline character.
If it is, then break out of the loop.
Check the current character to see if it's EOF.
If it is, then increment the line counter and break out of the loop.
That is how you deal with the final line not being terminated by a newline character and still have it counted as a line. Note that this is considered a special case and needs to be explicitly coded for. If you continue into the software development profession, then you will encounter special case situations a lot and you need to code the handling for each one that you encounter.
Hope this helps.
There was no issue with code; it work's fine, only the issue- it was taking input and was not giving output.
In windows to end input,
we have to press Ctrl + Z followed by Enter key, it will show the count of lines in input.
Your code is working properly.I checked it in Ubuntu.
Just press Ctrl+d if you are working in Linux to end the input.
This question already has an answer here:
C input - getchar()
(1 answer)
Closed 9 years ago.
I am runing the following simple program using Visual Studio 2010. The purpose is to see what will happen if I define variable c as char or int, since the getchar() function returns an integer (A widely known pitfall in the C programming language, refer to int c = getchar()?).
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF)
putchar(c);
printf("%d\n",c);
return 0;
}
When I input some characters from the console to this program, I found a strange phenomenon, as shown in the following figure. If the EOF as input follows a sequence of characters (the 1st line), it can not be correctly recognized (a small right arrow is ouput, 2nd line). However, if it is input standalone (4th line), it can be correctly recognized and the program terminates.
I didn't test this program on Linux, but can someone explain why this happen?
What you're describing is, basically, the way terminals are designed.
You need to remember that EOF is not a character. When you type "ABCDEFCTRL-Z", you're entering eight input characters: A, B, C, D, E, F, CTRL-Z, and Return. The only thing special about CTRL-Z (or CTRL-D on Unix/Linux) is that if you type that as the first thing on a new line, then instead of entering a character, the terminal behaves as though the end of the input file has been reached. The getchar() function will return EOF. Since any possible value that can fit into an unsigned char is a valid return value for getchar(), EOF can be distinguished from any valid return value by virtue of being negative, which is why getchar() and family are defined to return int.
If you change your program a little bit and put two printf statements, you will see that the program actually can read the CRTL+Z combination correctly (ASCII code 26):
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF) {
printf("%d\n",c);
putchar(c);
printf("\n");
}
printf("%d\n",c);
return 0;
}
But as the above answer tells, it must be on it's own line; in order to be interpreted correctly. Because on windows, each line has an EOL characters except the last line. There is an EOF character after the last line.