so I built a very basic program according to The C Programming Language book, but when I run it, it keeps asking input after I enter one, the loop should ended when there are no inputs longer right? or Am I wrong? srry for my bad english
int main()
{
long nc;
nc = 0;
while ( getchar() != EOF) {
++nc;
}
printf("%ld\n", nc);
}
Your loop is expecting an EOF character to terminate, not just an empty string. *nix consoles typically translate a Ctrl-D on an empty line as EOF, in Windows I believe it's Ctrl-Z but I could be wrong.
No.
For standard input, you must input EOF manually. It's Ctrl+Z in Windows and Ctrl+D in Linux.
If you are using Linux and redirect standard input from file. It will end.
This will keep reading input until it gets to an end-of-file. If you're reading from the terminal (you haven't redirected the program to read from a file), it will only get an EOF if you explicitly give it one. How you do that dpends on your OS, but on most UNIX-like systems, you can generate an explicit eof by hitting ctrl-D
You can press the Ctrl + D to input EOF, anything other keyboard can't! So if you want to interrupt the loop, you must input the EOF.
Related
This question already has answers here:
while ((c = getchar()) != EOF) Not terminating
(9 answers)
Closed 3 years ago.
I'm a beginner programmer (forgive this very basic question), and I am learning C through the Kernighan and Ritchie book "The C programming language".
I copied this program from the book, and it compiles fine, but when an input is given, the program does nothing.
#include <stdio.h>
int main() {
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%1d\n", nc);
}
The output is supposed to be the number of characters in the input, but nothing is happening
It will print the number of inputted characters when it has encountered the EOF (=end of file) condition.
If you're providing input through a terminal, there's no natural end of file
so you need to signal it with a special keyboard shortcut, which is typically either Ctrl+Z on Windows and Ctrl+D on a Unix system (Linux, MacOs, ...). (Windows also appears to require that you type an Enter both before and after the Ctrl+Z. The new-line character before the Ctrl+Z counts as another character, which effectively means that Windows, unlike Unixes, doesn't appear to allow you to have text-files that don't end with a new-line, at least with mingw gcc without cygwin.)
If you provide the input file through redirection as in ./a.out < some_file, then you don't have to worry about that because filesystem files have natural ends.
You are supposed to end the stream with an EOF indicator, which is CTRL+Z on Windows and CTRL+D on Linux based Operating systems. When getchar() reads EOF, it exists the while loop and the number of characters is output to stdout.
I am working on the infamous book "Prentice Hall Software Series" and trying out the Code they write and modifying it to learn more about C.
I am working with VIM on Fedora 25 in the console. The following code is a quote from the book, I know "int" is missing as well as argc and argv etc.
Kernighan and Ritchie - The C Programming Language: Page 20
#include <stdio.h>
/* copy input to output; 1st version */
main(){
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
With this code I couldn't manage to get the "EOF" to work. I am not sure if "ctr + z" really is the real thing to do, since it quits any console program in console.
Well since I was unsure i changed the condition to
...
while (c != 'a') {
...
So normally if I enter 'a' the while condition should break and the programm should terminate. Well it does not when I try to run it and enter 'a'. What is the problem here?
Thank you guys!
There's nothing wrong with the code (except the archaic declaration of main).
Usually, on Unixes end of file is signalled to the program by ctrl-D. If you hit ctrl-D either straight away or after hitting new-line, your program will read EOF.
However, the above short explanation hides a lot of subtleties.
In Unix, terminal input can operate in one of two modes (called IIRC raw and cooked). In cooked mode - the default - the OS will buffer input from the terminal until it either reads a new line or a ctrl-D character. It then sends the buffered input to your program.
Ultimately, your program will use the read system call to read the input. read will return the number of characters read but normally will block until it has some characters to read. getchar then passes them one by one to its caller. So getchar will block until a whole line of text has been received before it processes any of the characters in that line. (This is why it still didn't work when you used a).
By convention, the read system call returns 0 when it gets end of file. This is how getchar knows to return EOF to the caller. ctrl-D has the effect of forcing read to read and empty buffer (if it is sent immediately after a new line) which makes it look to getchar like it's reached EOF even though nobody has closed the input stream. This is why ctrl-D works if it is pressed straight after new line but not if it is pressed after entering some characters.
In section 1.5.2 of the 2nd ed. K&R introduce getchar() and putchar() and give an example of character counting, then line counting, and others throughout the chapter.
Here is the character counting program
#include <stdio.h>
main() {
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n",nc);
}
where should the input come from? typing into the terminal command window and hitting enter worked for the file copying program but not for this. I am using XCode for Mac.
It seems like the easiest way would be to read a text file with pathway "pathway/folder/read.txt" but I am having trouble with that as well.
From the interactive command line, press ctrl-D after a newline, or ctrl-D twice not after newline, to terminate the input. Then the program will see EOF and show you the results.
To pass a file by path, and avoid the interactive part, use the < redirection operator of the shell, ./count_characters < path/to/file.txt.
Standard C input functions only start processing what you type in when you press the Enter key IOW.Every key you press adds a character to the system buffer (shell).Then when the line is complete (ie, you press Enter), these characters are moved to C standard buffer. getchar() reads the first character in the buffer, which also removes it from the buffer.Each successive call to getchar() reads and removes the next char, and so on. If you don't read every character that you had typed into the keyboard buffer, but instead enter another line of text, then the next call to getchar() after that will continue reading the characters left over from the previous line; you will usually witness this as the program blowing past your second input. BTW, the newline from the Enter key is also a character and is also stored in the keyboard buffer, so if you have new input to read in you first need to clear out the keyboard buffer.
I wrote two programs in C to count characters and print the value.
One uses the while loop and the other uses for. No errors are reported while compiling, but neither print anything.
Here's the code using while:
#include <stdio.h>
/* count characters and input using while */
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
And here's the code using for:
#include <stdio.h>
/* count characters and input using for */
main()
{
long nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%ld\n", nc);
}
Both compile and run.
When I type input and hit enter, a blank newline prints. When I hit enter without inputting anything, again a blank newline prints. I think it should at least print zero.
You need to terminate the input to your program (i.e. trigger the EOF test).
You can do this on most unix terminals with Ctrl-D or Ctrl-Z at the start of a new line on most windows command windows.
Alternately you can redirect stdin from a file, e.g.:
myprogram < test.txt
Also, you should give main a return type; implicit int is deprecated.
int main(void)
Your programs will only output after seeing an end of file (EOF). Generate this on UNIX with CTRL-D or on Windows with CTRL-Z.
You wait for an EOF character (end of file) here. This will only happen in two scenarios:
The user presses Ctrl+Break (seems to work on Windows here, but I wouldn't count on this).
The user enters a EOF character (can be done with Ctrl+Z for example).
A better way to do this would be to check for a newline instead.
for your program to work correctly. after you press the enter key, u have to ensure that uyou terminate your loop, so that the program flos correctly. this is done by typing the ctrl+Z from your keyboard. these are the keys that correspond to the EOF.
Pressing Enter on your keyboard, adds the character \n to your input. In order to and the program and have it print out the number of characters you would need to add an 'End of File' (EOF) character.
In order to inject an EOF character, you should press CTRL-D in Unix or CTRL-Z on Windows.
You do realize that newline is a normal character, and not an EOF indicator? EOF would be Ctrl-D or Ctrl-Z on most popular OSes.
I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar() function.
For example this code:
#include <stdio.h>
main()
{
int c;
c = getchar();
putchar(c);
printf("\n");
}
Typing toomanychars + CTRL+D (EOF) prints just t. I think that's expected since it's the first character introduced.
But then this other piece of code:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
putchar(c);
}
Typing toomanychars + CTRL+D (EOF) prints toomanychars.
My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?
EDIT:
Thanks to everyone for the answers, I start to get it now... only one catch:
The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?
getchar gets a single character from the standard input, which in this case is the keyboard buffer.
In the second example, the getchar function is in a while loop which continues until it encounters a EOF, so it will keep looping and retrieve a character (and print the character to screen) until the input becomes empty.
Successive calls to getchar will get successive characters which are coming from the input.
Oh, and don't feel bad for asking this question -- I was puzzled when I first encountered this issue as well.
It's treating the input stream like a file. It is as if you opened a file containing the text "toomanychars" and read or outputted it one character at a time.
In the first example, in the absence of a while loop, it's like you opened a file and read the first character, and then outputted it. However the second example will continue to read characters until it gets an end of file signal (ctrl+D in your case) just like if it were reading from a file on disk.
In reply to your updated question, what operating system are you using? I ran it on my Windows XP laptop and it worked fine. If I hit enter, it would print out what I had so far, make a new line, and then continue. (The getchar() function doesn't return until you press enter, which is when there is nothing in the input buffer when it's called). When I press CTRL+Z (EOF in Windows), the program terminates. Note that in Windows, the EOF must be on a line of its own to count as an EOF in the command prompt. I don't know if this behavior is mimicked in Linux, or whatever system you may be running.
Something here is buffered. e.g. the stdout FILE* which putchar writes to might be line.buffered. When the program ends(or encounters a newline) such a FILE* will be fflush()'ed and you'll see the output.
In some cases the actual terminal you're viewing might buffer the output until a newline, or until the terminal itself is instructed to flush it's buffer, which might be the case when the current foreground program exits sincei it wants to present a new prompt.
Now, what's likely to be the actual case here, is that's it's the input that is buffered(in addition to the output :-) ) When you press the keys it'll appear on your terminal window. However the terminal won't send those characters to your application, it will buffer it until you instruct it to be the end-of-input with Ctrl+D, and possibly a newline as well.
Here's another version to play around and ponder about:
int main() {
int c;
while((c = getchar()) != EOF) {
if(c != '\n')
putchar(c);
}
return 0;
}
Try feeding your program a sentence, and hit Enter. And do the same if you comment out
if(c != '\n') Maybe you can determine if your input, output or both are buffered in some way.
THis becomes more interesting if you run the above like:
./mytest | ./mytest
(As sidecomment, note that CTRD+D isn't a character, nor is it EOF. But on some systems it'll result closing the input stream which again will raise EOF to anyone attempting to read from the stream.)
Your first program only reads one character, prints it out, and exits. Your second program has a loop. It keeps reading characters one at a time and printing them out until it reads an EOF character. Only one character is stored at any given time.
You're only using the variable c to contain each character one at a time.
Once you've displayed the first char (t) using putchar(c), you forget about the value of c by assigning the next character (o) to the variable c, replacing the previous value (t).
the code is functionally equivalent to
main(){
int c;
c = getchar();
while(c != EOF) {
putchar(c);
c = getchar();
}
}
you might find this version easier to understand. the only reason to put the assignment in the conditional is to avoid having to type 'c=getchar()' twice.
For your updated question, in the first example, only one character is read. It never reaches the EOF. The program terminates because there is nothing for it to do after completing the printf instruction. It just reads one character. Prints it. Puts in a newline. And then terminates as it has nothing more to do. It doesn't read more than one character.
Whereas, in the second code, the getchar and putchar are present inside a while loop. In this, the program keeps on reading characters one by one (as it is made to do so by the loop) until reaches reaches the EOF character (^D). At that point, it matches c!=EOF and since the conditions is not satisfied, it comes out of the loop. Now there are no more statements to execute. So the program terminates at this point.
Hope this helps.