C中的第二个和第三个gets()函数不起作用

时间:2016-08-14 16:52:35

标签: c

编译器没有显示任何错误,但第二个和第三个gets()函数似乎没有按预期工作。而是执行下一行代码。

#include <stdio.h>
#include <string.h>

struct student {
    char name[100], result[100];
    int marks;
} s1, s2, s3;

main() {
    printf("Enter the name of the student s1:");
    gets(s1.name);
    printf("Enter the marks obtained by the student s1:");
    scanf("%d", &s1.marks);
    printf("Enter the name of the student s2:");
    gets(s2.name);
    printf("Enter the marks obtained by the student s2: ");
    scanf("%d", &s2.marks);
    printf("Enter the name of the student s3:");
    gets(s3.name);
    printf("Enter the marks of the student s3:");
    scanf("%d", &s3.marks);
    if ((s1.marks > s2.marks) & (s1.marks > s3.marks))
        printf("the student s1 has got the highest marks");
    else 
    if ((s2.marks > s3.marks))
        printf("The student s2 has got the highest marks");
    else
        printf("The student s3 has got the highest marks");
}

enter image description here

3 个答案:

答案 0 :(得分:3)

这是因为您混淆了gets(已弃用 * )和scanf

来自scanf的行尾标记仍保留在缓冲区中,因此当gets尝试读取下一个输入时,它会将其视为空行。

您可以使用scanf对所有输入进行修复,包括字符串:

printf("Enter the name of the student s1:");
scanf("%99s", s1.name); // Use "%99[^\n]" to allow multi-part names
printf("Enter the marks obtained by the student s1:");
scanf("%d", &s1.marks);
不推荐使用

* gets,因此您应该使用fgets(s1.name, sizeof(s1.name), stdin)。以下是fgets的参考资料。

答案 1 :(得分:1)

使用scanf("%d ",&s1.marks);%d之后的空格将逃脱您在数字后输入的\n。如果我们不这样做,gets()会将"\n"读为下一个字符串输入。

答案 2 :(得分:0)

这应该有效:

#include <stdio.h>

struct student { 
  char name[100], result[100]; 
  int marks; 
} s1,s2,s3; 

int main() {
  printf("Enter the name of the student s1:"); 
  scanf("%s", s1.name);  
  printf("Enter the marks obtained by the student s1:"); 
  scanf("%d", &s1.marks); 
  printf("Enter the name of the student s2:"); 
  scanf("%s", s2.name); 
  printf("Enter the marks obtained by the student s2: "); 
  scanf("%d", &s2.marks); 
  printf("Enter the name of the student s3:"); 
  scanf("%s", s3.name); 
  printf("Enter the marks of the student s3:"); 
  scanf("%d", &s3.marks); 
  if ((s1.marks > s2.marks) && (s1.marks > s3.marks)) 
      printf("the student s1 has got the highest marks"); 
  else if((s2.marks > s3.marks)) 
      printf("The student s2 has got the highest marks"); 
  else 
      printf("The student s3 has got the highest marks");
  return 0;
}