How to read a random amount of integers in C?

2

I need to create a way to read integers in the same input, and the amount of integers entered is random every time the program is executed.

I tried to perform the following algorithm:

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

int main()
{
    long int numero, i, vetor[100000];

    i = 0;
    while(scanf("%li", &numero) != EOF)
        vetor[i++] = numero;

    while(i > 0)
        printf("%li ", vetor[i--]);

    return 0;
}

However, on a machine, the 1st while never ends. And on another machine, I get a segmentation fault. What could be happening?

    
asked by anonymous 09.04.2014 / 19:58

2 answers

3

Your problem and using scanf()

while(scanf("%li", &numero) != EOF)

The value that scanf() normally returns corresponds to the number of assignments made (in this case this value is 1 because only a variable is assigned numero ).

Note that a scanf() with more than one attribution can return a lower number without being an error

chk = scanf("%d%d%d", &um, &dois, &tres);
if (chk == 3) /* 3 atribuicoes */;
if (chk == 2) /* 2 atribuicoes: 'tres' nao foi atribuido */;
if (chk == 1) /* 1 atribuicao: apenas 'um' foi atribuido */;
if (chk == 0) /* nenhuma atribuicao */;
if (chk == EOF) /* erro de leitura */;

In your example above you should not test the value returned by scanf() with EOF , but with 1

while(scanf("%li", &numero) == 1)
    
09.04.2014 / 20:55
1

I made some small changes to your code and tried using CTRL + Z to stop the integers from reading, it worked fine:

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

int main()
{
    long int numero, i = 0, vetor[100000];

    while(scanf("%li", &numero) != EOF)
    {
        if (i == 99999)     //caso o vetor chegue ao seu limite a leitura encerra.
        {
            printf("Limite do vetor atingido!\n");
            break;
        } 
        else 
        {
            vetor[i++] = numero;
        }
    }

    while(i > 0)
        printf("%li ", vetor[--i]);

    return 0;
}

Take the test using this code, if there is any problem let me know in the comments I'm going to try to solve it. I hope I have helped.

    
09.04.2014 / 20:21