#include <stdio.h>
#include <stdlib.h>
struct Person{
char codeChacter[20];
char fullName[30];
int Iq, Eq;
};
int main(){
struct Person cha1, cha2;
printf("Enter detail of character 1: \n");
printf("code Character: ");
gets(cha1.codeChacter);
fflush(stdin);
printf("Full Name: ");
gets(cha1.fullName);
fflush(stdin);
printf("Enter Iq and Eq: ");
scanf("%d%d", &cha1.Iq, &cha1.Eq);
printf("Enter detail of character 2: \n");
printf("code Character: ");
gets(cha2.codeChacter);
fflush(stdin);
printf("Full Name: ");
gets(cha2.fullName);
fflush(stdin);
printf("Enter Iq and Eq: ");
scanf("%d%d", &cha2.Iq, &cha2.Eq);
printf("\n---------------------Detail------------------\n");
printf("%s\t%s\t%d\t%d\n", cha1.codeChacter, cha1.fullName, cha1.Iq, cha1.Eq);
printf("%s\t%s\t%d\t%d\n", cha2.codeChacter, cha2.fullName, cha2.Iq, cha2.Eq);
return 0;
}
这是我的第一个结构程序。当我运行这个应用程序时,它可以工作,但它不符合我的想法。那么你能帮我改变我的失败吗?非常感谢!
最佳答案
scanf("%d%d", (pointers to read));
不会从输入流中删除换行符,然后 gets
将读取换行符,并且不会按“预期”工作。
- 不要使用
fflush(stdin);
,这是未定义的行为。 - 不要使用
gets()
,这有缓冲区溢出的风险。
可能的修复:
#include <stdio.h>
#include <stdlib.h>
struct Person{
char codeChacter[20];
char fullName[30];
int Iq, Eq;
};
char* read_line(char *out, size_t bufsize){
char *lf;
if (fgets(out, bufsize, stdin) == NULL) return NULL;
/* remove the newline character because fgets store it while gets donesn't */
for (lf = out; *lf != '\0'; lf++){
if (*lf == '\n'){
*lf = '\0';
break;
}
}
return out;
}
int main(void){
char read_buf[1024];
struct Person cha1, cha2;
printf("Enter detail of character 1: \n");
printf("code Character: ");
read_line(cha1.codeChacter, sizeof(cha1.codeChacter));
printf("Full Name: ");
read_line(cha1.fullName, sizeof(cha1.fullName));
printf("Enter Iq and Eq: ");
read_line(read_buf, sizeof(read_buf));
sscanf(read_buf, "%d%d", &cha1.Iq, &cha1.Eq);
printf("Enter detail of character 2: \n");
printf("code Character: ");
read_line(cha2.codeChacter, sizeof(cha2.codeChacter));
printf("Full Name: ");
read_line(cha2.fullName, sizeof(cha2.fullName));
printf("Enter Iq and Eq: ");
read_line(read_buf, sizeof(read_buf));
sscanf(read_buf, "%d%d", &cha2.Iq, &cha2.Eq);
printf("\n---------------------Detail------------------\n");
printf("%s\t%s\t%d\t%d\n", cha1.codeChacter, cha1.fullName, cha1.Iq, cha1.Eq);
printf("%s\t%s\t%d\t%d\n", cha2.codeChacter, cha2.fullName, cha2.Iq, cha2.Eq);
return 0;
}
使用这段代码,你必须在同一行输入Iq和Eq,并且在输入Iq和Eq之前不能插入任何空行,而使用scanf
的程序则不需要这样做.
关于c - 结构和刷新(stdin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611198/