tags:

views:

170

answers:

3

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:

http://stackoverflow.com/questions/1793616/why-doesnt-getchar-recognise-return-as-eof-in-windows-console

+7  A: 

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>
paxdiablo
Remnant
Remnant
paxdiablo
A: 

Replace:

printf("&.0f\n, nc);

to

printf("%.0f\n", nc);
Pavel Radzivilovsky
and what about ending that orphan "
jpinto3912
A: 

EOF is ^d for linux, ^z for windows, and supposedly ^n for apple. ^ is control and key

You might have to add a getchar(); before the last closing brace } , on some systems your terminal will close if you don't. It does using devc++.

joe