C scanf() 不解析我的输入

标签 c scanf

我正在编写一个 C 程序,该程序的目标是我只想输入 4 个学生的详细信息和结构。但我的程序缺少一些东西,所以我的程序在输入第一个学生详细信息后退出。请看这里

# include <stdio.h>

struct student
{
int no;
char name[20];
float marks;
}s[10];

int main()
{
int i,n;


printf(" enter number of students ");
scanf("%d",&n);

printf(" enter student Number Name marks ");
for(i=0;i<n;i++)
{
scanf("%d%c%f",&s[i].no,&s[i].name,&s[i].marks);
}
return 0;
}

即使我选择的学生人数为 4,输入一名学生详细信息后程序也会退出。

我在这里给出的输入

[root@localhost raja]# gcc -o s s.c
[root@localhost raja]# ./s
 enter number of students 4
 enter student Number Name marks 1 as 12.03
[root@localhost raja]# 

即使只输入了第一个学生的详细信息,它也会退出该计划。 帮助我。

最佳答案

这是正确的代码

# include <stdio.h>

struct student
{
  int no;
  char name[20];
  float marks;
}s[10];

int main()
{
  int i,n;


  printf(" enter number of students ");
  scanf("%d",&n);

  printf(" enter student Number Name marks ");
  for(i=0;i<n;i++)
  {
    scanf("%d%20s%f",&s[i].no,s[i].name,&s[i].marks);
  }
  return 0;
}

第一个错误是 %c 应该是 %s,因为您需要的是字符串而不是字符。 第二个是,当您期望 %s 时,您只需要传入变量名,因为它是一个数组,因此是一个指针。 s 之前的 20 指定 name 变量的字符串允许的宽度。如果名称输入字符串的长度超过 20,则会扰乱其他变量的输入,并且程序将终止或出现意外行为。

关于C scanf() 不解析我的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17499005/

相关文章:

c - 打印 SHA256 和

c - fgets() 和 scanf() 的区别

c - scanf() 在 ENTER 后不起作用

c++ - 将数据 float 到 uint8_t 和 memcpy ,返回 null

c - 使用 strtok 将事物放入单独的数组中

c - scanf 在 scanf 行上产生段错误

c - while 循环中的 scanf

c - 尝试打印最小、最大和平均值。最小的打印不正确

c - 如何将 4 个 modbus 寄存器(每个 16 位)转换为 C 中的双 float ?

c6386 写入时缓冲区溢出