【问题标题】:Optional parameters in fscanf [C]fscanf [C] 中的可选参数
【发布时间】:2013-10-24 20:01:48
【问题描述】:

您好,我正在努力为我的链接列表创建菜单。我被告知使用 fscanf 来接受输入,但我有一个用户可能并不总是输入的论点,特别是要添加到链接列表的数字。我设置 fscanf 的方式是读取一个字符、一个数字,然后是另一个字符([enter] 键)。例如。用户输入“a 20[enter]”将数字 20 添加到链表中。但是,如果用户输入“d[enter]”,那么 num 字段是无效的,因为用户输入了一个字符!注意我不能使用 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;
}

【问题讨论】:

  • scanf获取第一个字符,然后判断是否需要获取数字。另外,你能用getline()吗?
  • 不,只是 fscanf。也谢谢你的帮助,我试试看。

标签: c scanf


【解决方案1】:

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

【讨论】:

  • %s 只匹配到第一个非空白字符。哦,现在我重新阅读了他的问题,我猜输入没有像a20 这样的空格,尽管他写了“a 20
猜你喜欢
  • 2010-09-19
  • 2013-01-26
  • 2012-10-08
  • 2011-03-04
  • 2010-10-08
  • 1970-01-01
相关资源
最近更新 更多