fscanf [C]中的可选参数

时间:2013-10-24 20:01:49

标签: c scanf

您好我正在努力为我的链表创建菜单。我被告知使用fscanf接收输入,但我有一个参数,用户可能并不总是输入,特别是要添加到链表的数字。我设置fscanf的方法是读取一个char,一个数字,然后是另一个char([enter]键)。例如。用户输入“a 20 [enter]”将数字20添加到链表。但是,如果用户输入“d [enter]”,则num字段无效,因为用户输入了char!注意我不能使用fgets()。

我需要另一个fscanf字段吗?这是我的菜单代码:

int main(void) {
    struct node* head = NULL;
    int num, ret;
    char select = 'n';
    char c;
    while (select != 'e') {
        printf("Enter:\na(dd) (x) = add a new node with value x to the list at the front of the list\n");
        printf("d(el) = delete the first node of list\n");
        printf("l(ength) = print the number of nodes in the list\n");
        printf("p(rint) = print the complete list\n");
        printf("z(ero) = delete the entire list\n");
        printf("e(xit) = quit the program\n");          
        ret = (fscanf(stdin, "%c %d%c", &select, &num, &c));
        if (ret == 3 && select == 'a' && c == '\n')
            Add(&head, num);
        else if (ret == 2 && select == 'd')
            Delete(&head);
        else if (ret == 2 && select == 'l')
            Length(head);
        else if (ret == 2 && select == 'p')
            PrintList(head);
        else if (ret == 2 && select == 'z' )
            ZeroList(&head);
        else
            printf("invalid\n");
    }
    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:0)

scanf没有参数的默认值。使用fgets读取一行(this可能会帮助您)然后使用sscanf来解析输入。如果在fgets中输入的行以字符a开头,则使用sscanf(line,"%c %d %c", &select, &num, &c ),否则请使用sscanf(line,"%c %c", &select, &c )