Search code examples
cstringstreamscanfstring-parsing

Read a list of numbers from string


I want to read a list of space - separated numbers stored in a string.
I know how this can be done using stringstream in C++ -:

string s = "10 22 45 67 89";
stringstream ss(s);
int numbers[100];
int k=0, next_number;
while(ss>>next_number)
    numbers[k++]=next_number;

My question is how can we do this in C ? I have read about sscanf() in C but I am not certain it can be useful here.


Solution

  • You can use sscanf here if you know the number of items you expect in the string:

    char const *s = "10 22 45 67 89";
    
    sscanf(s, "%d %d %d %d %d", numbers, numbers+1, numbers+2, numbers+3 numbers+4);
    

    If, however, you don't know the number of items a priori, you might try tokenizing the input, then attempting to convert each item individually.

    char s[] = "10 22 45 67 89";
    
    char *n = strtok(s, " ");
    do { 
        numbers[k++] = atoi(n);
    } while (n = strtok(NULL, " "));
    

    Note that strtok has quite an ugly interface--it modifies the string you pass to it, and requires that you use it roughly as above--you pass the input string in the first call, then pass NULL for the string to tokenize for subsequent calls until you reach the end of the string. It stores a pointer to the current location in the string internally, which also makes thread safety a problem.

    You can also use sscanf with the %n conversion to count the number of characters already converted, but that's (IMO) in nearly direct competition with strtok for some of the ugliest code imaginable, and I can't handle posting two things like that in one day.