When I comnpile And run the program nothing appears,i'm using codeblocks 17.12 please help me.
ANSWER: To make the result of printf appear you should end the cycle with ctrl+z or ctrl+d depending if you are using windows or linux.
main()
{
int nc;
for (nc=0; getchar() !=EOF; ++nc);
printf("%d\n", nc);
return 0;
}
for (nc=0; getchar() !=EOF; ++nc);
the ';' at the end of the line is perhaps not what you want, because of it the body of the for is empty
so printf("%d\n", nc); is executed only one time, not several, and for that you need first to go out of the for, so to reach EOF
What is your OS, what are you doing to have EOF ?
If you never reach EOF it is normal to have nothing print
If you are under Linux/Unix you can do echo blahblah | ./yourprog and yes in that case you will print 9 (because of the newline, 8 if echo -n blahblah)
Under Windows do not execute your code through codeblocks, execute it directly in a terminal, codeblocks and other IDE have unexpected behavior on the input/output
Related
Following "The C Programming Language" by Kernighan and Ritchie, I am trying to enter the program described on page 18 (see below).
The only changes I made were to add "int" before "main" and "return 0;" before closing the brackets.
When I run the program in Terminal (Mac OS 10.15) I am prompted to enter an input. After I enter the input I am prompted to enter an input again - the "printf" line is apparently never reached and so the number of characters is never displayed.
Can anyone help me with the reason why EOF is never reached letting the while loop exit? I read some other answers suggesting CTRL + D or CTRL + Z, but I thought this shouldn't require extra input. (I was able to get the loop to exit with CTRL + D).
I have also pasted my code and the terminal window below.
#include <stdio.h>
int main(){
long nc;
nc = 0;
while( getchar() != EOF )
++nc;
printf("%ld\n", nc);
return 0;
}
From pg. 18 of "The C Programming Language
My screenshot
You already have the correct answer: when entering data at the terminal, Ctrl-D is the proper way to indicate "I'm done" to the terminal driver so that it sends an EOF condition to your program (Ctrl-Z on Windows). Ctrl-C breaks out of your program early.
If you ran this program with a redirect from an actual file, it would properly count the characters in the file.
EOF means end of file; newlines are not ends of files. You need to press CTRL+D to give the terminal an EOF signal, that's why you're never exiting your while loop.
If you were to give a file as input instead of through the command line, then you would not need to press CTRL+D
Adding to the two good answers I would stress that EOF does not naturally occur in stdin like in other files, a signal from the user must be sent, as you already stated in your question.
Think about it for a second, your input is a number of characters and in the end you press Enter, so the last character present in stdin is a newline character not EOF. For it to work EOF would have to be inputed, and that is precisely what Ctrl+D for Linux/Mac or Ctrl+Z for Windows, do.
As #DavidC.Rankin correctly pointed out EOF can also occur on stdin through bash piping e.g. echo "count this" | ./count or redirecting e.g. ./count < somefile, where somefile would be a text file with the contents you want to pass to stdin.
By the way Ctrl+C just ends the program, whereas Ctrl+D ends the loop and continues the program execution.
For a single line input from the command line you can use something like:
int c = 0;
while((c = getchar()) != EOF && c != '\n'){
++nc;
}
I'm trying to learn C Language, and I'm reading and testing a lot about it, but sometimes is difficult to understand why somethings just don't work as expected. Why the example code showed on page 18 of The C Programming Language, Second Edition (Kernighan and Ritchie), don't work? It doesn't show any results for me.
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf ("%ld\n", nc);
}
It doesn't show anything because it's waiting for input.
If you're running this like ./the_executable, it'll always be reading your input because of getchar(). And it'll show the results only after the input stream ends.
You can cut it off manually by pressing Control+D. Or use the contents of a file as input:
./the_executable < test_file.txt
The C Programming Language, Second Edition by Brian Kernighan and Dennis Ritchie is a very good book, but it is quite old and refers to an outdated definition of the C language. The program you posted uses an obsolete syntax for main. It should be modified as:
#include <stdio.h>
int main() {
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
return 0;
}
As you can see, the difference is minimal and in this particular case, the above version would also compile with the pre-ansi compilers in use at the time the book was written.
The program reads bytes from the standard input and just counts how many it could read before reaching the end of file.
You should run this program from a terminal window and type some data and signal the end of file by pressing Ctrl and D on unix systems such as linux and OS/X or Ctrl and Z followed by Enter on Microsoft systems.
You can also redirect input from a file and will get the number of bytes in this file, possibly adjusted on Microsoft systems due to line ending conversion.
Running the program directly from an IDE is not demonstrative because IDE's usually do not keep the terminal window open when the program exits, preventing the user from seeing the final output.
It should indeed work as expected.
The reason why you are confusing it with not working because you are expecting printf to print something for you (value of nc), but the catch is there is another statement getchar() before printf which is reading standard input with the help of while loop until you input EOF which is entered by ^D (control + D) in unix, like cat command if you used on *nix or by redirecting input to your program from a file using < operator, like
./a.out < someFile.txt
You have to enter the "end of file" condition. So ctrl Z or ctrl C should work.
#include <stdio.h>
int main(){
int c, nl=0;
while((c = getchar()) != EOF)
if(c=='\n')
nl++;
printf("%d",nl+1);
return 0;
}
On Ubuntu 18.04, GCC 7.3.0
There's no output on console when the getchar() comparison is made with EOF. it works fine with other characters. Using CTRL^D exits the program with 'code 0' without any output on console. I've tried running it in bash but still no output.
input:
line 1
line 2
line 3
line 4
line 5
expected output:
5
actual output:
program exited with code 0
On *nix systems EOF is generated by Ctrl^D whereas on Windows system EOF is generated by Ctrl^Z. I am assuming that you are using Windows system. See https://en.wikipedia.org/wiki/End-of-file
These programs are meant to read input from file. so on bash if you do this:
./linecount < textfile.txt
will give you the output
5
but i guess in editors using ctrl^D to generate/trigger EOF character doesn't work well.(At least not on mine).
I'm doing homework for my C programming class. The question states "Write a program which reads input as a stream of characters until encountering EOF". I'm using Xcode on my macbook and the only way I know to make the program encounter EOF is using ctrl + D or ctrl + Z. But it will exit my program completely.
For example I have this code:
int main()
{
int ch;
while ((ch = getchar()) != EOF)
{
putchar(ch);
}
printf("%d",ch);
return 0;
}
Is there away for the code to execute the printf("%d",ch) after the loop (after i hit ctrl + D on my keyboard)?
You can test your program using (with a POSIX shell) here documents.
First compile your source code mycode.c into a binary mybin with
gcc -std=c99 -Wall -Wextra -g mycode.c -o mybin
(it could be clang or cc instead of gcc)
then run mybin with a "here document" like
./mybin << EOF
here is my
input
EOF
You could also use input redirection. Make some file myfile.txt and run ./mybin < myfile.txt
You could even run your program on its own source code: ./mybin < mycode.c
And the input could even come from some pipe, e.g. ls * | ./mybin
BTW, what you are observing is that stdin, when it is a terminal, is line-buffered. See this answer (most of it should apply to MacOSX).
Notice that your code is incorrect: you are missing an #include <stdio.h> near the top of the file, and your main should really be int main(int argc, char**argv) (BTW you could improve your program so that when arguments are given, they are file names to be read). At last the ending printf would surely show -1 which is generally the value of EOF
Also, it is much better to end your printf format control string with \n or else use appropriately fflush(3)
Notice that end-of-file is not an input (or a valid char), it is a condition on some input file stream like stdin, and the getchar(3) function is specified to return EOF which is an int outside of the range of char (on my Linux system EOF is -1 because char-s are between 0 and 255 included). You might test end-of-file condition after some input operation (never before!) using feof(3)
A terminal in usual cooked mode is handled by the kernel so that when you press Ctrl D an end-of-file condition is triggered on the file descriptor (often STDIN_FILENO i.e. 0) related to that terminal.
I'm using Xcode on my macbook and the only way I know to make the program encounter EOF is using ctrl + D or ctrl + Z. But it will exit my program completely.
No it won't. If you run your program in the Xcode debugger, provided the console pane has the focus, all input you type will go to your program (note that, by default, stdin is line buffered, so you'll only see output when you press the return key). If you hit control-d (not control-z), you're program will exit the loop and print -1 in the console window (which is what you expect because that is the value of EOF in OS X).
Here is the result when I ran your program without change in the Xcode debugger (I typed command-r in Xcode)
bgbgdfsfd
bgbgdfsfd
hgfdgf
hgfdgf
-1
Regular font was typed by me, bold font was from your program. At the end of each of the lines typed by me, I pressed carriage return. After your program printed hgfdgf I typed control-D. Your program then printed the value of the last thing it got from getchar() which was EOF which is -1 in the OS X C library.
Edit
If you are unsure that your program is printing the EOF, change your printf format string to (for example)
printf("Last character is [%d]\n", ch);
Then instead of -1 your program will output Last character is [-1] on the last line.
First of all ctrl+z does not input EOF to your program. If you hit ctrl+Z your shell will put your program to sleep.
Second, if you want to handle these ctrl+Z in your program you need to learn about signal handling in C.
And I think because you were hitting ctrl+Z you were not seeing any output on the screen.
Make sure you are sending the EOF signal, not a signal that actually terminates your program.
For example, for c program running in windows the EOF is represent by typing ctrl+z and pressing enter. Doing this will exit your while loop but still runs the rest of your program.
However, ctrl+c, which some people may have mistakenly tried for EOF, actually kills your program and will prevent the code behind your while loop from executing.
For mac you will need to find what is the input that corresponds to EOF, and make sure that is what you are sending through rather than the kill signal, which I suspect is what you are doing here.
I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this:
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
When I run the program, it opens a window I can type in, but when I hit enter all that happens is it skips down a line and I can keep typing, but I think it's supposed to print the number of characters.
Any idea what's going wrong?
This line:
while (getchar() != EOF)
means that it keeps reading until the end of input — not until the end of a line. (EOF is a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.
If you want to terminate on EOL (end of line), replace EOF with '\n':
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != '\n')
++nc;
printf("%ld\n", nc);
}
Enter is not EOF. Depending on your OS, Ctrl-D or Ctrl-Z should act as EOF on standard input.
I ran into the problem tonight, too. Finally found out that Ctrl-D on Linux worked. You build the source file using cc, and start the program and input a word, then press Ctrl-D twice when finished typing. The number that the program countered will be printed just behind the very word you just typed, and the program terminates immediately. Just like this:
The above answer provided by nujabse is correct. But recently coming across this issue myself and researching the answer, I would like to add why.
Using Ctrl+C tells the terminal to send a SIGINT to the current foreground process, which by default translates into terminating the application.
Ctrl+D tells the terminal that it should register a EOF on standard input, which bash interprets as a desire to exit.
What's the difference between ^C and ^D