Harveybegood
Harveybegood

Reputation: 53

C Program will not stop encountering EOF or -1

I am new beginner in C programming language.

Program will not stop from for or while loop if input is EOF or -1.

The program is like below:

#include <stdio.h>
int main() {
    double nc;
    for (nc = 0; getchar() != EOF; ++nc) {
        printf("%.0f\n", nc);
    }
}

From my understanding, if I input EOF or -1 in terminate then the for loop will be stopped, as -1 or EOF makes the condition being false.

One more question regarding the same example: if I will not use nesting loop code as followings:

for (nc = 0; getchar() != EOF; ++nc)
    ;
printf("%.0f", nc);

No any error or alert, but it seems function printf does not work as expected. It just output what I input.

Upvotes: 3

Views: 980

Answers (3)

chqrlie
chqrlie

Reputation: 144645

Your program will stop at end of file, which is what EOF signifies.

To enter an end of file from the terminal, type Ctrl-D on unix or Mac/OS and Ctrl-ZEnter on Windows systems.

Ctrl-D is obtained by pressing Ctrl and then D while the Ctrl key is held down.

Note that a double variable is not appropriate for a simple counter, you should favor the int type for this.

Note also that input is not received one character at a time by the program: it may be buffered on a line basis when reading from the terminal and on a block basis when reading from a file. A posted, your program will read a line of input from the terminal and as multiples lines of output at once, one for each character typed, including the newline.

Upvotes: 4

Aconcagua
Aconcagua

Reputation: 25518

You misunderstood...

If you enter EOF or -1 in console, you will get these as strings: "EOF", "-1". If you read them character by character, you will get the sequences 'E', 'O', 'F' and '-', '1' (numerical values, ASCII/UTF-8 provided: 69, 79, 70 and 45, 49 respectively), but never the numerical value of EOF(-1).

How to actually enter EOF: see chqrlie's answer, who has been faster than me...

Upvotes: 0

Attie
Attie

Reputation: 6969

EOF is not something that you can input, rather a state the the file descriptor can be in.

To achieve this state on the console you must press Ctrl+D if you're running a unix-like system.


Alternatively if you were to run your application by feeding in a file, you'd see that your application will stop once it has read to the end of the file.

./my_app < some_file.txt

Additionally, I would advise you to use an integer type to count loop iterations, for example int, or size_t. Floating point types are not well suited to this.

Upvotes: 2

Related Questions