William Deaver
William Deaver

Reputation: 23

example C program doesn't work and has weird behavior when useing getchar()

I'm trying to learn c with K&R, but have hit an issue; not all cod seems to be executed?

I'm on 1.5.2: character counting; I think this is the exact wording of the example:

#include <stdio.h>

/* count characters in input; 1st version */
main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
} 

It's supposed to take an input, count the number of characters until an EOF character, then print only the total.

However, once I compile and run it in the terminal, it doesn't seem to do anything:

eli@eli-Laptop:~/programing$ gcc hello.c -o hello
hello.c:4:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
    4 | main()
      | ^~~~
eli@eli-Laptop:~/programing$ ./hello
test
testonetwo
^C
eli@eli-Laptop:~/programing$ 

This was a weird failure mode, so I tried commenting it up:

#include <stdio.h>

/* count characters in input; 1st version */
main()
{
    long nc;
    nc = 0;
    printf("start, is %ld\n ");

    while (getchar() != EOF){
        ++nc;
        printf("middle; so far is %ld\n", nc);
    }

    printf("end; is %ld\n");
}

however, when I try it, I get this:

eli@eli-Laptop:~/programing$ ./hello
start, is 0
test 
middle; so far is 1
middle; so far is 2
middle; so far is 3
middle; so far is 4
middle; so far is 5
test2
middle; so far is 6
middle; so far is 7
middle; so far is 8
middle; so far is 9
middle; so far is 10
middle; so far is 11
^C
eli@eli-Laptop:~/programing$ 

This has me pretty much stumped; it looks like once the while exits the program just finishes? and when I put something else it looks like only the while loop is run; at the start the total is not reset and print is not run, and at the end the final print still doesn't run.

I'm new to programming without an IDE, so this may just be an issue with not knowing how command line works.

Upvotes: 2

Views: 80

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

To generate the EOF condition you need to press either CTRL+D or CTRL+Z depending on whether you are using a UNIX system or a Windows system.

Upvotes: 2

Kevin
Kevin

Reputation: 7334

When you hit ctrl-C, your terminal sends the SIGINT (interrupt) signal to your program. By default this terminates the program.

To tell your program that it's reached the end of the input, you need to hit ctrl-D instead. getchar() will then return EOF and the loop will exit.

Upvotes: 4

Related Questions