I have experience in C++ so admittedly this shouldn't be too hard for me to understand but I guess it is. Im learning C from K&R's "The C Programming Language". I am performing this example from Chapter 1 Page 18, the example at the bottom of the page.
#include <stdio.h>
int main(){
double nc;
for(nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f \n", nc);
return 0;
}
I am redirecting input from the keyboard to instead be read from a text file (using the '<' when running a.out), and the text file has absolutely nothing in it, not even a newline character.
The program prints a 1. Shouldn't it be 0? Is there a character that is being read that isn't an EOF value? Or is the for loop executing its contents once, then increment by 1, then check the condition?
Thank you for the help!
Related
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!
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.
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.
For reasons of self-improvement / broadening my horizons I have decided to learn some of the fundamentals of C using the K&R 'C Programming Language Book'.
I have been following along with the exercises, using Bloodhsed DEV C++ 4.9.9.2 as my IDE.
I came across the following exercise - counting characters in an input:
main()
{
double nc;
for(nc = 0; getchar() != EOF; ++nc);
printf("&.0f\n", nc);
}
This code complies and runs without error.
However, when I enter a string in the console window and press enter I do not get any output i.e. a number that shows how many characters in the string. For example, if I type 'test' in the console window I am expecting 4 to appear as output.
I am sure the issue is simply the way I have set up my IDE? Or am I missing something more fundamental?
Any help much appreciated. Having come from a VB background I am really excited about learning a different language like C and getting to grips with pointers!
Edit
A related answer to my question is also given here and is very helpful:
Why doesn't getchar() recognise return as EOF on the console?
You won't get any output until the standard input stream is closed (with either CTRLZ under Windows or CTRLD under various UNIX flavors).
The newline is just another character.
You may also want to get a more recent C tutorial book. main() is no longer one of the mandated main prototypes for ISO C, you should be using one of:
int main(void) {}
int main(int argc, char *argv[]) {}
On top of that, your code as shown won't compile since you don't terminate the printf format string. Use:
printf("%.0f\n", nc);
instead of:
printf("&.0f\n, nc);
Why you're using a double is also a mystery unless you want to process really large files - I'd be using an int or a long for that.
Here's the code I'd be using:
#include <stdio.h>
int main (void) {
long nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%ld\n", nc);
return 0;
}
which produces the following session:
pax> countchars
Hello there.<ENTER>
My name is Bob.<ENTER>
<CTRL-D>
29
pax>
Replace:
printf("&.0f\n, nc);
to
printf("%.0f\n", nc);
The code you had given is correct but seems it doesn't work. In my case also it was not working, so i just replaced EOF with '\n' and it has worked for me but for only one line, as after press enter it gives the output and program ends.
Please find the complete code below:
#include <stdio.h>
/* Count characters in input; version 2*/
int main(void)
{
double nc;
for (nc = 0; getchar() != '\n'; ++nc);
printf("%.0f \n", nc);
return 0;
}