【发布时间】:2016-09-28 12:36:15
【问题描述】:
这个程序有什么问题??我从 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);
}
以下是一些屏幕截图:
我不知道也不知道出了什么问题。请帮我.. 提前谢谢..
【问题讨论】:
-
最简单的解决方法:
char dummy; scanf("%d%c", &choice, &dummy);您的scanf正在读取整数值并将'\n'(输入键盘按钮的ASCII 值)汽车放入stdin缓冲区。所以你必须在阅读新内容之前先进行假脱机。 -
它解决了第一个问题。当我输入 saugat 进行选择时,它会显示输出,显示您的名字是 saugat.. 我该如何解决?
-
我没有得到你。你能详细说明一下吗?您的代码应该在输入名称后输出
printf("Your name is : %s",temp.name);。 -
我的代码在那一刻显示(你的选择是什么:)不要输入数字只需输入一个字符串...它显示名称而不是执行 if/else 条件它不起作用正确...请帮助我..
-
如果
scanf格式说明符是%d,则不能输入字符串。您应该检查scanf的返回值以检查它是否失败。
标签: c gcc gcc-warning gcc4 gcc4.7