Alex P
Alex P

Reputation: 12497

Getting started with C using K&R C Programming Language Book

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: Why doesn't getchar() recognise return as EOF on the console?

Upvotes: 2

Views: 1241

Answers (3)

Vino
Vino

Reputation: 922

The code you had given is correct but seems it doesn't work. In my case also it was not working, so i just replaced EOF with '\n' and it has worked for me but for only one line, as after press enter it gives the output and program ends. Please find the complete code below:

#include <stdio.h>
/* Count characters in input; version 2*/

int main(void)
{
    double nc;
    for (nc = 0; getchar() != '\n'; ++nc);
    printf("%.0f \n", nc);
    return 0;
}

Upvotes: 0

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

Replace:

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

to

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

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 882756

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>

Upvotes: 10

Related Questions