U
U
unit_9112020-07-30 15:41:19
C++ / C#
unit_911, 2020-07-30 15:41:19

Why doesn't outputting the value of a variable work in a for loop?

B. Kernighan and D. Ritchie "The C Programming Language, 3rd Edition, Revised", CLion 2019.3.3, C99 version.

#include <stdio.h>
//подсчет количества вводимых символов
int main() {
    double nc;
    for (nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%.0f,", nc);
}

The author of the book says that the loop body cannot be empty, and we put a semicolon. But this code doesn't work correctly. It is expected to count all the characters entered in the string and output that value. However, after typing characters and pressing Enter, the terminal doesn't output anything else. If you put the printf function inside the for loop itself, the terminal prints the values ​​(0, 1, 2, .., x), as it should. I have several options why this happens:
1. In that code, the value of the nc variable only works inside the loop, and since we did not assign at least zero to the variable before the loop, there is nothing to display. (because through the while loop with the addition of a value at the end of the loop body, everything also does not work)
2. The value of the EOF constant does not work correctly, and therefore the loop does not end
3. Something else that I don't know yet (I'm completely new)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Demin, 2020-07-30
@unit_911

Everything works correctly, you just need to add an end-of-file character to the end of the input text. On linux this is done by pressing Ctrl-D, on windows - Ctrl-Z

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question