【发布时间】:2016-01-24 06:07:28
【问题描述】:
我想写一个小程序来学习C;在这里:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int total;
char suffix[3];
struct person {
char id[11];
char name[21];
char sex[7];
int age;
char phone[12];
};
char* number_suffix (int number) {
int mod;
mod = number % 10;
switch (mod) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
return suffix;
}
void input_info (struct person info[], int total_people) {
int counter;
for (counter=0; counter<total_people; counter++){
printf("%s%d%s%s\n","Please input the ID(10 digits) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].id);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Name(20 chars) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%[^\n]", info[counter].name);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Sex(Male/Female) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].sex);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Age(1~100) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%d", &info[counter].age);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Phone of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].phone);
fflush(stdin);
}
printf("%s\n%s\n%s\n%d\n%s\n", info[counter].id, info[counter].name, info[counter].sex, &info[counter].age, info[counter].phone);
}
int main (void) {
printf("%s\n", "Please input a number that how many people you want to record:");
scanf("%d", &total);
fflush(stdin);
struct person *person_info = malloc(sizeof(struct person)*total);
input_info(person_info, total);
free(person_info);
return 0;
}
当我运行它时,我发现了一些奇怪的东西。
Please input a number that how many people you want to record:
1
Please input the ID(10 digits) of 1th person:
A01
Please input the Name(20 chars) of 1th person:
Please input the Sex(Male/Female) of 1th person:
Male
Please input the Age(1~100) of 1th person:
32
Please input the Phone of 1th person:
1224464
[empty line]
[empty line]
[empty line]
1926234464
[empty line]
该程序在运行时是否跳过scanf("%[^\n]", info[counter].name); 这一行?
为什么,是什么原因造成的?
【问题讨论】:
-
fflush(stdin)不推荐。在许多实现中,刷新输入流是未定义的行为。在您的特定情况下,它可能不会摆脱第一个scanf留下的换行符。见scanf Getting Skipped -
"如何理解指针、struct、malloc、函数参数之间的关系?" -- 什么?这太宽泛了,无法回答。所以,我已经删除了它。
-
详情请咨询Using
fflush(stdin)— 除非您使用的是 Windows 系统,否则它不会执行您想要/期望的操作。 -
打印
counter+1时需要调用number_suffix(counter+1)。别忘了它是11th、12th和13th(但1st和21st、2nd和22nd、3rd和23rd)。 -
总的来说,你应该每次检查
scanf()的结果,以确保你得到了你期望的结果。调试问题时的一项基本技术是回显您刚刚获得的输入,以确保计算机得到您期望的结果。
标签: c pointers struct parameters malloc