How to scanf commas, but with commas not assigned to a structure? C

前端 未结 3 1130

I want to scanf input like: \"John, Surname, 9999\" and commas should not be assigned to the scanned variable; spaces at the end and start of input deleted... Now t

3条回答
  •  情话喂你
    2020-12-21 23:02

    scanf has several pitfalls, especially when using it for scanning several separated input fields using a single statement / format string. For example, the new line character is treated as a white space just as a blank, and this can achieve weird results when reading in multiple lines. Further, you'd probably want to protect your code from being broken by "too long" user input; so you'd write "%19s ...", but then the remainder of the input will be passed to the next format specifier...

    These pitfalls let people tend to say "use fgets and parse the input on your own, e.g. by using strtok. The code gets "longer", but you get much more control over edge cases.

    See the following code using such an approach:

    int main()
    {
        struct student_t s;
        struct student_t *p = &s;
    
        char buffer[1000];
        if (fgets(buffer,1000, stdin)) {
            char *name = strtok(buffer,",");
            if (name) {
                sscanf(name," %19s", p->name);  // skip leading spaces
                char *surname = strtok(NULL,",");
                if (surname) {
                    sscanf(surname," %39s", p->surname); // skip leading spaces
                    char *index = strtok(NULL,",");
                    if (index) {
                        p->index = (int)strtol(index, NULL, 10);
                    }
                }
            }
        }
    
        return 0;
    }
    

提交回复
热议问题