Reading a string with spaces with sscanf

前端 未结 5 922
终归单人心
终归单人心 2020-11-28 05:47

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 spa

5条回答
  •  情深已故
    2020-11-28 06:04

    If you want to scan to the end of the string (stripping out a newline if there), just use:

    char *x = "19 cool kid";
    sscanf (x, "%d %[^\n]", &age, buffer);
    

    That's because %s only matches non-whitespace characters and will stop on the first whitespace it finds. The %[^\n] format specifier will match every character that's not (because of ^) in the selection given (which is a newline). In other words, it will match any other character.


    Keep in mind that you should have allocated enough space in your buffer to take the string since you cannot be sure how much will be read (a good reason to stay away from scanf/fscanf unless you use specific field widths).

    You could do that with:

    char *x = "19 cool kid";
    char *buffer = malloc (strlen (x) + 1);
    sscanf (x, "%d %[^\n]", &age, buffer);
    

    (you don't need * sizeof(char) since that's always 1 by definition).

提交回复
热议问题