jsantos
jsantos

Reputation: 302

How to scan an unknown number of elements from a string?

I'm trying to scanf multiple ints from a string, but I don't know how many it will have, because it varies from case to case. I want to scanf multiple numbers and put them in an array.

I've been trying to do it this way but it's not working... Assuming I want to scan C numbers from the string "line".

for(a=0;a<c;a++)
    sscanf(line, " %d ",&v[a]);

Upvotes: 2

Views: 1227

Answers (3)

jsantos
jsantos

Reputation: 302

I finally nailed it! Thanks for all your help guys ;)

f = fopen(argv[1],"r");
fgets(line,c,f);

line2 = strtok(line, " ");

while (line2 != NULL){

    sscanf(line2, "%d",&v[i]);

    line2=strtok(NULL, " ");
    i++;
}

Upvotes: 0

MYMNeo
MYMNeo

Reputation: 836

I wrote a piece of code to help you understand it more clearly.

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

int main(void){
    int v[10];
    char buffer[4096];

    char * line = NULL;
    int i, j;


    if(fgets(buffer, 4096, stdin) == NULL){
        return -1; 
    }   

    for(i = 0, line = strtok(buffer, " "); i < 10; i++){
        if(line == NULL){
            break;
        }   

        sscanf(line, "%d", &v[i]);
        line = strtok(NULL, " "); 
    }   
    j = i;

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

    return 0;
}

[neo]:./a.out 
1 2 3 4 5 9999
1
2
3
4
5
9999

Upvotes: 1

MYMNeo
MYMNeo

Reputation: 836

Suppose you have enough space to store as much as integer.

char * c_num = NULL;
for(c_num = strtok(line, " \t\n"), a = 0; c_num != NULL && a < c; c_num = strtok(NULL, " \t\n"), a++){
    v[a] = atoi(c_num);
}

Upvotes: 1

Related Questions