Reading numbers in C

Asked

Viewed 60 times

2

I wrote this code to read multiple numbers on the keyboard. I want the reading to end when the user presses Enter. But when I press Enter, he keeps waiting for new entrances.

#include <stdio.h>

int main() {
    while (!feof(stdin)) {
        int x;
        if (scanf("%d", &x) == 1) {
            printf("%d\n", x);
        }
    }
    return 0;
}

This is the first time I’ve programmed in C. Does anyone know how to get the program to stop reading when the user presses a new line?

1 answer

2

If running on a terminal, what generates EOF is Ctrl+D (Linux/Unix) or Ctrl+Z (Windows). Type ENTER generates a valid entry, then feof will return false and the loop continues.

Here’s another detail: if you don’t enter a valid number (for example, "Xyz"), your code will go into loop, for scanf does not clear these characters from buffer incoming.

Instead, you could trade scanf for fgets, which reads a line (all that was typed up to the ENTER), and after reading you check if you only have one ENTER, which in this case will be represented by the line break (\n - since the fgets includes the line break in the read string):

#include<stdio.h>
#include<stdlib.h>

int main() {
    char buffer[20]; // defina um tamanho razoável para os números que você quer ler
    while (fgets(buffer, sizeof buffer, stdin)) { // se der erro na leitura (por exemplo, um EOF), sai do while
        if (buffer[0] == '\n') // se digitou somente ENTER, sai do while
            break;
        // tenta transformar em número (usando a base 10)
        printf("%ld\n", strtol(buffer, NULL, 10));
    }
    return 0;
}

Once read and checked that not only has a line break, I try to convert to number with strtol. The code is still not very robust because it does not check if there was error in the conversion (which is a bit boring to do, see here and here).
It also doesn’t treat cases of having more than one number on the same line (separated by space, for example), or if you type more characters than the buffer size, etc. Anyway, C is a "raw" language and allows/"requires" that in practice you yourself end up creating your data entry functions, with the specific behaviors you want it to have. But the general idea is this.


In fact the subject is broader than it seems, as every detail of the code can unfold into a "world apart" (as for example "do not use while (! feof)", "avoid scanf to read entries typed by the user", etc). Therefore, I recommend that you read here, here, here, here, here, here, here and here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.