Read multiple integers in the same input in C

Asked

Viewed 5,760 times

0

Basically, I must enter a number that represents the amount of integers to be entered. Then insert the integers themselves, separated by space, into the same input.

Example:

5
1 2 3 4 5

I tried to perform the following repetition, without much hope knowing that there was anything strange:

i=0;
scanf("%i", &numeros);
long int *vetor = malloc(numeros*sizeof(long int));

while(numeros > 0)
{
    scanf("%i", &vetor[i]);
    i++;
    numeros--;
}

If we insert the example up there, the vector does not receive the first integer, and the last receives garbage. Something like: [2, 3, 4, 5, -13343256]

How could I read these integers from the same input?

  • 2

    Could post the code of how you did the test?

  • 1

    I discovered the error by debugging.

  • 1

    Your code seems to work well, see Osvaldo’s response. I also tested it here.

2 answers

1

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

 int main(void)
 {
    printf ("digite qtd de numeros\n");
    scanf("%d", &numero);

    int vetor[numero];
    int x, i;

    printf ("digite o numeros\n");

    for (i = 0; i < numero; i++)   /*Este laço faz o scan de cada elemento do vetor*/
    {
       scanf("%d", &vetor[i] );
    }

    printf("\n Concluído");
    getch ();
    return 0;
 }
  • 1

    Uou, read http://answall.com/editing-help and [Answer]. Code-only answers solve the problem but teach nothing. Explain the why values much more.

  • The only difference from your code from mine is that you have declared a static vector at compile time, but it needs a value entered by the user. I thought this could generate error, or at least a Warning.

  • 1

    This does not cause warnings. In these cases of academic exercises it is common to implement so. It is also possible to implement dynamically. Either way will give the same result.

1


long int *vetor = malloc(numeros*sizeof(long int));
    scanf("%i", &vetor[i]);

To read long int you can’t use "%i".

Or declare your array as int *vetor, or use "%li" in the scanf.


If the problem persists, it should be in print. In C, the indices of the array begin in 0.

An array of 5 elements has Indice of 0 to 4 (and not of 1 to 5).

  • 1

    Thanks for the remark, but that’s not the problem yet.

  • 1

    Nor is that, because I don’t print the vector. I debuggged the program and put watches in all vector positions. In the first passage of the repetition, vector[0] = 2, and should receive 1.

Browser other questions tagged

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