Store values of a string in an array

Asked

Viewed 1,797 times

0

I need to make a program in C that takes a sequence of numbers, stores the values in a vector and then prints this sequence in the reverse order. It must receive two entries, the first is an integer number indicating how many numbers the sequence has, and the second is the sequence of numbers (each number is separated only by a 'blank space'), as follows in the example:

4

2 51 8 10

To read the string I thought to use the function:

char sequencia[100]; 

scanf("%[^\n]",sequencia); 

However I am not able to separate the values and store inside an integer vector. How can I solve this problem?

  • 1

    Why read as string ? use scanf("%d")

  • using scanf(%d) how do I have each value stored in a different position? Obs: the sequence is passed to the program in a single string, each value is separated by a 'space' only

  • is it mandatory that the numbers are separated by spaces? The numbers could not be typed separately?

  • Create an array of size 100 (I’m assuming 100 because Voce used the size of your string) for int values ... and use a;

  • the question asks that they be separated by spaces only, the only way I thought of doing this was to read as a string and separate the values using space as delimiter

2 answers

1

To answer your question: use fgets() to read strings with spaces.

Attention that the fgets() stores the final ENTER of each line. If necessary clear this ENTER before processing the string further.

char input[100];
if (fgets(input, sizeof input, stdin) == NULL) /* erro */;
/* se necessario remove ENTER final de input */

But for your needs, you can use the conversion "%d" of scanf(), which reads characters and interprets as a number automatically:

int n;
int k;
if (scanf("%d", &n) != 1) /* erro */; // primeiro número
for (k = 0; k < n; k++) {
    if (scanf("%d", &sequencia[k]) != 1) /* erro */; // números seguintes
}

Note: for the scanf() format "%d" spaces, Enters, Tabs before the number are automatically ignored.

0

If the values you have to collect are only integers, you can do so:

...
int *y;
int x,i;
if(scanf("%i", &x); != -1){
    y = (int *) malloc(sizeof(int)); // Aloca um tamanho para y
    for(i=0;i<x;i++)
        scanf("%i", &y[i]);
}
...
  • The cast (explicit conversion) to the value returned by malloc() is, at best, redundant; and can hide an error that the compiler would pick up in his absence.

Browser other questions tagged

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