当我执行scanf以获取“name”时,它跳过了自己,我应该做什么改变才能让它不这样做?

osh3o9ms  于 2023-03-07  发布在  其他
关注(0)|答案(3)|浏览(114)
#include <stdio.h>

int b;
int main()
{
int a, c;
printf("Enter the number of students \n");
scanf("%d", &a);

struct studinfo{
    char name[50];
    int roll;
    float marks;
};

struct studinfo s[10];

for(int i = 0; i <= a; i++)
{
    printf("Enter the Name :\n");
    scanf("%[^\n]s", s[i].name);      //THIS ONE HERE
    printf("\n");
    printf("Enter the roll no. \n");
    scanf("%d", &s[i].roll);
    printf("\n");
    printf("Enter the marks\n");
    scanf("%f", &s[i].marks);
}

for(int i = 0; i<= a; i++)
{
        printf("Name: %s\n", s[i].name);
        printf("Roll no: %d\n", s[i].roll);
        printf("Marks: %f", s[i].marks);
}
return 0;
}
Works when I remove the scanf to enter number of students.

包括<stdio.h>

int b; int main(){int a,c;printf("输入学生人数\n");

struct studinfo{
    char name[50];
    int roll;
    float marks;
};

struct studinfo s[10];

for(int i = 0; i <= a; i++)
{
    printf("Enter the Name :\n");
    scanf("%[^\n]s", s[i].name);
    printf("\n");
    printf("Enter the roll no. \n");
    scanf("%d", &s[i].roll);
    printf("\n");
    printf("Enter the marks\n");
    scanf("%f", &s[i].marks);
}

for(int i = 0; i<= a; i++)
{
        printf("Name: %s\n", s[i].name);
        printf("Roll no: %d\n", s[i].roll);
        printf("Marks: %f", s[i].marks);
}
return 0;

}

-> This happenes because the Scanf initially used takes everything except for '\n' which is later is read by the next scanf which skips when it reads a '\n'.
-> Ive tried Fgets and gets too but still doesnt work.
- 

The output im getting is;

after I enter the number of students, it just skips the scanf to enter the name and just executes scanf to enter the roll no.
whlutmcx

whlutmcx1#

scanf(" %[^\n]", s[i].name);
scanf中的空白字符(空格、制表符等)(通常使用空格)读取连续的空白字符,直到出现非空白字符。
%[]之后没有。

bvn4nwqk

bvn4nwqk2#

对于初学者,您应该检查a的值不大于10,并且for循环中的条件应该如下所示

struct studinfo s[10];

for(int i = 0; i < a; i++)

至于你的问题,那么在这次scanf的通话之后

scanf("%d", &a);

输入缓冲区包含新的行字符'\n',它对应于按下的Enter键。

scanf("%[^\n]s", s[i].name);

读取一个空字符串。并且格式字符串中有多余的s字符。
你应该写

scanf( " %49[^\n]", s[i].name );
       ^^^^^^^^^^

注意格式字符串中的前导空格。它允许跳过白色字符。

3j86kqsm

3j86kqsm3#

  • "eat"第一次输入\n:
scanf("\n%[^\n]", s[i].name);

祝你好运
提示

  • 限制输入长度:%49 [^\n]以限制要读取的字符数。
  • 将for循环结束条件更正为:i〈a

相关问题