Reading a string with spaces with sscanf

前端 未结 5 934
终归单人心
终归单人心 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 05:57

    Since you want the trailing string from the input, you can use %n (number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.

    const char *input = "19  cool kid";
    int age;
    int nameStart = 0;
    sscanf(input, "%d %n", &age, &nameStart);
    printf("%s is %d years old\n", input + nameStart, age);
    

    outputs:

    cool kid is 19 years old
    

提交回复
热议问题