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;
}
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!
I'm working through the K&R C book and one of the example programs is this:
#include <stdio.h>
int main() {
long nc;
nc = 0;
while (getchar() != EOF) {
++nc;
}
printf("%ld", nc);
return 0;
}
When I run this program, it mostly behaves as I expect. So for an input like This is a sentence, it prints 19.
However, if I input anything under 10 characters (including EOF), there is a capital D appended to the output number.
E.g. for input hello, the output is 6D.
Why is there a D appended to an integer value and what does it mean?
Note: This occurs with cc, gcc and clang.
It turns out that D is part of the ^D that gets printed to the console when I input an EOF (control + D on Unix). Because there is no \n at the start of the printf statement, a single-digit number will overwrite the ^, while a double-digit number will overwrite the entire ^D, which is what gave the impression of some weird behaviour.
What version of gcc are you using? I ran the exact same code using gcc and it runs fine. Maybe it's an artifact left over by your terminal where it's trying to print the Ctrl-D for end of file
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.
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!
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.