这个程序有什么问题?我试图弄清楚,因为2天,但没有任何帮助! 字符串输出仅在字符串输入之后并且在选择选项之后,默认字符串输入是默认的新行字符。 此外,如果我在输入选项时键入字符串,它会默认显示名称输出。这是我的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct marks {
char subject[15];
int mark;
};
struct student {
char name[10];
int roll;
struct marks m[3];
};
void displayData(struct student);
int displayChoice();
struct student getNewRecord();
int main() {
struct student s[5];
int count = 0;
int choice;
do{
choice = displayChoice();
if(choice == 1){
s[count] = getNewRecord();
count ++;
}
else if(choice == 4)
break;
else
printf("Invalid choice");
}while(1);
}
struct student getNewRecord() {
struct student temp;
printf("Enter your Name : ");
fgets(temp.name, 10,stdin );
printf("Your name is : %s",temp.name);
return temp;
}
int displayChoice() {
int choice;
printf("\n\nPlease select your choice :\n");
printf("1. Add new Record\n");
printf("2. Display All data \n");
printf("3. Remove last Record\n");
printf("4. Exit the program\n");
printf("What is your choice : \n");
scanf("%d", &choice);
return choice;
}
void displayData(struct student s){
printf("Your name : %s", s.name);
}
以下是一些屏幕截图:
我不知道,也不知道出了什么问题。请帮我.. 提前谢谢..
答案 0 :(得分:0)
您的代码存在一些问题:
'\n'
char留给stdin
,下一次调用从stdin读取的函数会立即退出该字符。scanf
的返回值,以确保用户输入了有效的数字。(void)
s
数组大小。您可以为stdin
添加一个空函数,例如:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct marks {
char subject[15];
int mark;
};
struct student {
char name[10];
int roll;
struct marks m[3];
};
void displayData(struct student);
int displayChoice(void);
struct student getNewRecord();
void flush_stdin(void);
int main(void)
{
struct student s[5];
size_t count = 0;
int choice;
do{
choice = displayChoice();
if(choice == 1)
{
s[count] = getNewRecord();
count ++;
}
else if(choice == 4)
break;
else
printf("Invalid choice");
}
while ((count < sizeof(s)/sizeof(s[0]) ) && (choice != 4));
}
struct student getNewRecord(void)
{
struct student temp;
printf("Enter your Name : ");
scanf("%s", temp.name);
printf("Your name is : %s", temp.name);
flush_stdin();
return temp;
}
int displayChoice(void) {
int choice;
printf("\n\nPlease select your choice :\n");
printf("1. Add new Record\n");
printf("2. Display All data \n");
printf("3. Remove last Record\n");
printf("4. Exit the program\n");
printf("What is your choice : \n");
if (scanf("%d", &choice) != 1)
{
choice = 99;
}
flush_stdin();
return choice;
}
void displayData(struct student s)
{
printf("Your name : %s", s.name);
}
void flush_stdin(void)
{
int c;
while ( ((c = getchar()) != '\n') && (c != EOF) );
}