【发布时间】: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。也谢谢你的帮助,我试试看。