我想写一个小程序来学习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);
这行吗?
为什么,是什么导致它?
答案 0 :(得分:1)
fflush(stdin)
未定义,但它适用于某些实现。但最好避免它,因为它不可移植,可能会调用未定义的行为。
要解决此问题,请将所有fflush(stdin)
替换为
int c; /* Declare it once */
while((c = getchar()) != '\n' && c != EOF); /* Discards everything until a newline character or EOF */
另一个问题是
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);
应该是
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);
并且应该将放在 for
循环中。否则,您调用未定义的行为,因为
int*
%d
,希望int
。此外,正如其他人所说,将counter + 1
传递给number_suffix
。
答案 1 :(得分:1)
" %[^\n]"
代替"%[^\n]"
无法捕获\n
(之前的数据输入后)counter + 1
传递给number_suffix
如何理解指针,struct,malloc,函数参数之间的关系?
从 O&#39; Reilly Media
中阅读Understanding and Using C Pointers