Read multiple scanf numbers separated by space

Asked

Viewed 7,818 times

-2

I need to make a program that receives a number of elements from a vector, and then each element of that vector, but in the same scanf with spaces. Only I don’t know how to do this, someone can help me.

Example:

3
1 2 3
  • What is the programming language? " C" ?

  • Sorry, it’s in C

  • Put an example of what you did, it will be easier for someone to help you.

  • ta in vector and you want to read? did not understand this scanf define better please.

  • Type, the user type how many elements the vector will have, and then in a scanf have to put these elements separated by a space.

3 answers

2

If you want to read several separate numbers of space, then you want to read it all as one string and basically make split on a certain separator, in this case the space. The easiest and native way to do this is to use strtok. This function reads a part of a string until it picks up the specified tab, and then from the last point it is possible to call again to pick up another bit.

Example:

int quant;
scanf("%d", &quant);
int vetor[quant];
char nums[512]; //espaço para os numeros todos como um texto
scanf(" %[^\n]", nums); //lê todos os números como um texto
char *token = strtok (nums," "); //lê até ao primeiro espaço para a variavel token
int pos = 0; //posição para guardar os numeros no vetor começa em 0

while (token != NULL && pos < quant) {
    vetor[pos++] = atoi(token); //guarda o valor convertido em numero no vetor e avança
    token = strtok (NULL, " "); //lê até ao próximo espaço a partir de onde terminou
}

Conversion of text to number was done with atoi. It’s important to note that the rest strtok not the first, they take as the first parameter NULL to indicate that they are sequels to the previous.

Now just use the number array:

int i;
for (i = 0; i < tamanho; ++i){
    printf("%d\n", vetor[i]);
}

That gives you the following exit:

1
2
3

See code working on Ideone

  • What happens if I type more than 512 characters?

  • @Marcelouchimura Goes beyond the limits of the allocated space and writes in a memory zone that does not belong to the vector. Naturally you can put another value that you think is reasonable for the expected input, like 1024, 2048, 4096, etc. But there already begins to enter another problem that has already passed here other questions that is like reading "unlimited input" in C. I just put one that seemed reasonable to me for the input example you gave.

  • There is input limited? How much do you expect to be a vector size reasonable?

  • 1

    @Marcelouchimura "How much do you expect to be a reasonable vector size?" - Only you can say, after all you know what the program will serve and what it will do. "Is there limited input?" - How do you read a string in C ? Do not previously declare the chars array ? You have to put there the size otherwise it bursts the program with a Segmentation fault, so it is not unlimited no. The limit depends on what you wrote there.

  • @Marcelouchimura It is worth remembering that you can always control whether the input exceeded the set size with scanf(" %512[^\n] and making an additional test to know if the last character read was \n or by changing the scanf by a fgets which would even be the most advised. I just didn’t do it to try to keep the answer simple.

  • Where do I find reference on [^\n]? Is this standard/recommended? Any C compiler supports this?

  • @Marcelouchimura The reference is in the documentation of scanf same. You can see here. The most recommended is to use fgets which was excluded by the restriction of the question, yet if validated against the size has no problem. All compilers support this yes.

Show 2 more comments

1

If I understand correctly you are trying to read numbers and insert in a vector, being that these trying to make this reading with more than one number... Follow the example:

#include<stdio.h>
#include<stdlib.h>
#define N 3
 int main()
 {
 int i,x;
 int v[N];
 scanf("%d %d",&i,&x);
 v[0]=i;
 v[1]=x;
 v[2]=0;

 } 

This is a small example... scanf("%d %d",&x,&i);
Follows the always % criteria with the type of variable in case d or i of decimal or integer (%d) repeats more than once if it is more than one variable and then uses the &.

  • Almost that, only that type, I don’t know how many elements the user wants, so if for example he wants 10 elements, the code would be very large. I was wondering if there’s any way to narrow it down.

  • Vectors are finite, you will have a predetermined space number. And the scanf tu need not do everything together in the same, makes with a loop of repetition and le normal. Can not?

0

I couldn’t find a way to pass a vector or a pointer to a vector, to a scanf. See if this way helps you:

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

void pegaVetor(int* vetor, int qtd)
{
    int i;

    fflush(stdin);
    printf("Entre o vetor, abaixo:\n");
    for (i = 0; i < qtd; ++i)
    {
        scanf("%d", &vetor[i]);
    }
}

double media(int* vetor, int qtd)
{
    int i;
    int soma = 0;

    for (i = 0; i < qtd; ++i)
    {
        soma += vetor[i];
    }

    return (double)soma / qtd;
}

int main()
{
    int* vetor;
    int n;

    do
    {
        fflush(stdin);
        printf("Digite o numero de elementos (0 para sair): ");
        scanf("%d", &n);
        if (n)
        {
            vetor = (int*)malloc(n * sizeof(int));
            pegaVetor(vetor, n);
            printf("A media aritmetica do vetor e: %f\n", media(vetor, n));
            free(vetor);
        }
    } while (n);

    return 0;
}

Possible input token delimiters, for the scanf, are blanks and/or Enters.

Browser other questions tagged

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