Reading a string with spaces with sscanf

SDLFunTimes picture SDLFunTimes · May 18, 2010 · Viewed 117.9k times · Source

For a project I'm trying to read an int and a string from a string. The only problem is sscanf() appears to break reading an %s when it sees a space. Is there anyway to get around this limitation? Here's an example of what I'm trying to do:

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

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid", "%d %s", &age, buffer);

    printf("%s is %d years old\n", buffer, age);
    return 0;
}

What it prints is: cool is 19 years old where I need cool kid is 19 years old. Does anyone know how to fix this?

Answer

BrunoLM picture BrunoLM · May 18, 2010

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);