I am a new learner of C language. I recently got to know about the getchar() function. I wrote a program to count number of words in an input. The program goes as follows: (I AM USING CODEBLOCKS):
#include <stdio.h>
main(){
int c, nw; /*nw stands for NUMBER OF WORDS*/
while((c=getchar())!=EOF){
if (c==' '||c=='\t'||c=='\n')
++nw;
}
printf("NUMBER OF WORDS ARE:%d",nw);
}
When I run the program, it takes the input, but there is no OUTPUT. It just keeps on taking the input no matter how many times you press enter.
I tried to search for this a million times but I couldn't find the answer.
However, someone told me to include a Ctrl+D break in the while loop. I tried to do that but same result.
Please if someone has a solution help me. From past 2 weeks I am trying to figure out the problem.
Thanks!
Your loop will end when it encounters EOF(-1).
It just keeps on taking the input no matter how many times you press enter.
Because '\n' != EOF.
To stimulate EOF,
Press CTRL+Z if you are using windows/DOS. This must be followed by Enter
Press CTRL+D if you are on UNIX/Linux/OSX. This flushes the stdin there are characters to be flushed. Otherwise, it sends EOF to the stdin.
BTW, as others have noticed, you need to initialize nw to 0. Also, the signature of main should be int main(void).
Related
I just wanted to ask what the importance of using getch() is, especially in this array/for-loop example that our professor showed us:
int i;
char pw[7], ch;
printf ("\npw: ");
for (i=0; i<7; i++) {
ch = getch();
pw[i] = ch;
printf ("%c", ch);
}
I tried removing the ch = getch() line and what happened when I ran the program was that the loop went on forever.
Why does that happen?
I only understand that getch() is used at the end of a program to not show a character on the screen (from online definitions).
getch() reads a character from the keyboard without echoing it.
so your program is reading a character from the keybord (user input). and storing it in ch variable, then saving it in the string array pw[], at the end echoing it using printf("%c");
by removing ch = getch();. your program stops reading from keyboard. and fills the pw[] with the same value of (uninitialized ) ch exactly 7 times, and then exit loop.
according to what you posted, you program hangs elsewhere, where you are testing the validity of the password.
If you comment out getch line it runs and ends, it does not loop forever, you must have removed more to change it into a loop forever. To answer your initial question [getch] gets a char and then the program displays it, that's all.
Getch() - Reads a single character from STDIN, if none exists, waits for it!
In your example, Getch() plays a central role, reading the user input (given 7 characters).
if you remove this statement, not only you leave int ch uninitialized (with no valid value),
but the loop wont wait for anything (as getch() won't wait).
Sometimes, especially when learning c++, running a simple program from Visual Studio (or whatever IDE you use)...
running the program is very short, and you cant see the output!
so one adds getch(); at the end, just to tell the program to wait for any character, or put differently, leave the window open and wait for my key-press.
Sorry for asking such a simple question, I'm still learning C and going through the basics first.
I'm creating a character counting program and yet when I execute the program and try to input "h" for example and then press enter a new line appears and nothing is outputted onto that line?
Code:
#include <stdio.h>
/* Copy input and count characters 2nd version */
main() {
double cc;
for(cc = 0; getchar() != EOF; ++cc);
printf("%.0f\n", cc);
}
Once you have finished entering characters, you have to signal the end of input stream by pressing Ctrl-D. Otherwise your program will continue waiting for more input.
P.S. Why are you using a double variable for the counter? An integer type would be more appropriate.
Maybe (I'm not sure what exactly do you want) you have an extra ; after the for(), which mean an empty statement. So your program will run the empty statement (in other words, do nothing) until the end of input (if the input is terminal, you may need a CTRL+D), and then print (once) the number of characters.
If you want your program to print the counter after every char in the input, remove that ;, so the printf will be in the loop.
Include this line at the end you will get output:
return 0;
I'm a middle experienced Java developer and have many problems learning the C language for my computer science study. I try it with the book "The C Programming Language" which many people seem to recommend.
But I've got problems with the simplest stuff like the EOF in combination with getchar(). Here's the code:
#include<stdio.h>
main()
{
int i = 0;
while (getchar() != EOF)
{
++i;
printf("Count of characters is %d", i);
}
}
I'm working with Mac OS X Lion and use the "cc" command with "./a.out" for running in terminal, like described in the book to run the file. And what I get is:
Always counting one character too much
the while loop never ends! it just waits for another input after reaching end of input ...
I really have no idea what could be the issue. Can someone help?
Always counting one character too much
That could be the newline (enter / return).
the while loop never ends! it just waits for another input after
reaching end of input
You are likely not signaling end of input. You should be using CTRL-D to do so.
When you type a character, such as "6" and you click enter (which is equal to \n), then the command "6\n" is sent, so it is 2 characters. If you just press enter, then 'i' will be increased by 1.
The EOF means end of file and its equivalent to ctrld+D. It is useful if you read a text file. Else it is the same as saying "Forever".
Ok I'm just learning C and stumble upon this practice code to count character K&R's book:
#include <stdio.h>
/* count characters in input; 2nd version */
main()
{
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
The problem is I don't know whether is it suppose to print the amount of characters or not when I entered any character because there is no output whatsoever, just whitespace (getchar() waiting for another input).
Can someone explain to me what is going on? I'm practicing in bash using vim in openSUSE 11.3.
You have to send the EOF signal/character to the program. If you are running it from inside a terminal window, press Ctrl+D.
If you are piping from a file, like so:
./my_program < input_file_name
then it will work automagically.
Since it is checking for EOF, hit Ctrl-D in the terminal.
As others have mentioned, you have to press control-d (aka ^d) but that only works after you hit return. In other words you cannot type "foocontrol-d" and expect it to work. "fooreturncontrol-d" would work, though.
Also please note that K&R is a fine fine book, but was written decades ago. The counting algorithm presented only work on ASCII-ish input. Wide characters (UTF-8, etc) would not be counted correctly.
Also also note, the example you quoted is using a floating point number for this counting. There is little strictly wrong with this, but for speed and efficiency, most people would use unsigned ints, longs, or some other intergral datatype. You are not likely to be reading ¾th of a character!
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.