【发布时间】:2016-03-24 10:44:43
【问题描述】:
我正在尝试编写一个基于菜单的小程序来维护记录。 用户输入要用于存储的总人数(名字、姓氏、分数)的数字。用户在一行上输入所有信息,用空格分隔,我将它们分成 3 列(名字、姓氏、分数),然后按 Enter 并继续输入更多信息,直到达到最大人数。
我的问题是,当我运行它时,它不能正常工作;它运行并接受用户输入,但仅适用于两个学生(即使我一直在使用大于 5 的数字作为测试用例),然后程序立即结束(没有错误代码,只是结束......)并且它没有甚至进入菜单。谁能告诉我我的代码有什么问题?
int i, j, count, numberPeople, temp, choice;
char people[15][3], tempArr[20];
char *token;
printf("Please indicate number of records you want to enter (min 5, max 15): ");
scanf("%d", &temp);
while ((temp > 15) || (temp < 5)) {
printf("\nNumber not in specified range, try again.\n");
printf("Please indicate number of records you want to enter (min 5, max 15): ");
scanf("%d", &temp);
}
numberPeople = temp;
printf("\nEnter the first name, last name, and grade (put a space in between each): ");
for (i = 0; i < numberPeople; i++) {
fgets(tempArr, 20, stdin);
token = strtok(tempArr, " ");
for (j = 0; j < 3; j++) {
while (token != NULL) {
people[i][j] = *token;
printf("%s\n", token); // this is here to as a test case to see if my data was being stored.
token = strtok(NULL, " ");
}
}
}
已编辑:将 scanf 更改为 fgets
输出
Please indicate number of records you want to enter (min 5, max 15): 5
Enter the first name, last name, and grade (put a space in between each): firstname1 lastname1 85
firstname1
lastname1
85
firstname2 lastname2 84
firstname2
lastname2
Program ended with exit code: 0
【问题讨论】:
-
为什么你的 for 循环中嵌套了一个 while 循环?
-
scanf("%s")一次读取一个“单词”,以空格分隔。使用fgets()读取整行,然后使用strtok()将其拆分。您可以通过在阅读后立即打印出计算机读取的内容来帮助自己;这是最基本的调试形式,但仍然非常有价值;它会告诉您发生了什么(您为 2 个用户输入 6 个单词,因此在读取第二个数字之前满足循环到 5)。
标签: c