【发布时间】:2015-02-21 19:22:20
【问题描述】:
我有一个struct person,它具有以下元素,在data.h 中定义
typedef struct person{
char firstName[20];
char familyName[20];
char telephoneNum[20];
int type; // 0 = student / 1 = employee;
}newPerson;
我创建了一个person[MAX_PERSONS] 数组,该数组在我的menu() 函数中初始化。然后我有一个addFirstName(newPerson pers) 函数。但是,当我尝试使用 printFormat(newPerson pers)function 测试打印格式时,我得到空白,而不是输入的名称。
我在下面包含了 menu()、addFirstname(newPerson pers) 和 printFormat(newPerson pers) 函数。我想知道是否有人可以告诉我这样做的原因。任何帮助或指示将不胜感激。提前谢谢你。
int menu(){
int num = 0;
newPerson person[MAX_PERSONS];
int option; // for user input for menu
printf("\n\tPlease choose one of the following options to continue (0-9): ");
scanf("%d", &option );
printf("\n\tYou selected %d\n", option);
if (option == 0){ //program will close
printf("\tProgram will now close.\n");
exit(1);
}
if (option == 1){ //program will ask for name input
addRecord(person[num]);
printFormat(person[num]);
char choice[0];
printf("\n\t\tWould you like to enter another record? (y/n): ");
scanf("%s", choice);
if (choice[0] == 'y'){
num++;
addRecord(person[num]);
}
if (choice[0] == 'n'){
num++;
mainMenu();
}
/*
IF YES, THEN NUM++
THEN RUN ADDRECORD(PERSONNUM) AGAIN.
IF NO, THEN RETURN TO MAIN MENU.
PRINTMENU
THEN RUN MENU AGAIN
*/
}
printf("\n\tNot a valid option, please try again // THE END OF MENU FUNCTION\n");
return 0;
}
void addFirstName(newPerson pers){
char firstName[20];
printf("\n\tEnter first Name: ");
scanf("%20s", firstName);
strcpy(pers.firstName, firstName);
printf("\n\tThe name entered is %s", pers.firstName);
}
void printFormat(newPerson pers){
printf("\t\tThe name is %s", pers.firstName);
}
【问题讨论】:
-
不要忽略
scanf()的返回值。另外,scanf("%20s", firstName);是错误的,应该是scanf("%19s", firstName);,不需要临时缓冲区,可以直接scanf("%19s", fpers.firstName);避免strcpy()。
标签: c string printing struct format