Counting character code in C - c

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!

Related

What is the intended input method to ANSI C Second Edition exercise problems?

I am doing Kernighan/Ritchie ANSI C Second Edition exercises in the first chapter. Problem is, the book didn't teach you yet about argv/argc or fopen, yet it uses such a structure where if you just run your program and give input at runtime, you will get into an infinite repetition of the test (c = getchar()) != EOF because getchar() at runtime will prompt the user for input as soon stdin is empty, and when the user gives input, the input will process, and getchar() will prompt for another input. EOF will literally never get encountered.
My mentors told me that you can input an EOF with ctrl+d, but that is obviously a hack and not intended.
Another solution they gave me is a.out <<< "some string" which actually works and does have EOF, but now I am at a point where I have to have an input of multiple lines, and I have no idea how to input lines like this, and frankly I heard that <<< didn't even exist in 1989.
Here is a code example of the type of problem:
#include <stdio.h>
/* count characters in input; 1st version */
int main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
So how did programmers feed input in this kind of program back in the day? Mind you, you are only allowed to use the things the book taught you until now (which is literally nothing about input)

getchar() and conditioning a loop to break with a specific char

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.

Importance of using getch() inside a for-loop

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.

No output in word count program in C

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).

Very basic example code of "The C Programming Language" doesn't work like expected?

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".

Resources