Store values of a string in a vector

0

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

4

2 51 8 10

To read the string I thought about using the function:

char sequencia[100]; 

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

But I'm not able to separate the values and store them inside a vector of integers. How can I resolve this problem?

    
asked by anonymous 29.02.2016 / 17:06

2 answers

1

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

Note that fgets() saves 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 "%d" conversion of scanf() , which reads the characters and interprets as numbers 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% w / o% w / w format% spaces, ENTERs, TABs prior to number are automatically ignored.

    
29.02.2016 / 17:23
0

If the values you have to collect are just integers, you can do this:

...
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]);
}
...
    
29.02.2016 / 23:43