C:结构用法

标签 c

<分区>

printf("enter nation\n") 之后的行; to printf("输入 m 或 f\n");没有像代码块那样执行看不到它,因为它打印了两行,我没有机会在两者之间输入任何东西。这个问题总是在我使用 struct 时发生

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct emp
{

int salary;
int age;
char name[10];
char m:1;
char nation:1;

};
int main()
{
int i,k;
char g,n;
char name2[10];
struct emp x[3];
for(i=0;i<3;i++)

    {
         printf("enter name\n");
         scanf("%s",&name2);
         strcpy(x[i].name,name2);


        printf("enter salary\n");
         scanf("%d",&x[i].salary);
        printf("enter age\n");
         scanf("%d",&x[i].age);



          printf("enter nation\n");

看不到接下来的 3 行并跳转输入 m 或 f

          scanf("%c",&n);
          if(n=='e'){x[i].nation==0;}
          else {x[i].nation==1;}

          printf("enter m or f\n");

也看不到那些线条

          scanf("%c",&g);
          if(g=='f'){x[i].m=0;}
          else if(g=='m'){&x[i]==1;}



    }

    for(k=0;k<3;k++)
        {
            if(x[i].nation=='e')
            {
                puts(x[i].name);
                printf("%d\n",x[i].salary);
                printf("%d\n",x[i].age);
                if(x[i].m==0)
                printf("female\n");
                else {printf("male\n");}
                printf("egyptian");

                }


        }

return 0;

}

最佳答案

你必须改变

scanf("%c",&n);

scanf(" %c",&n); // Skip leading whitespaces

C中的数组是通过指针传递的,所以对于

char name2[10];

你不必使用引用运算符

scanf("%s",&name2);

只是简单地做

scanf("%s",name2);  // Will pass an arrays address

另外最好限制输入,否则可能会发生缓冲区溢出并导致未定义的行为

scanf("%9s",name2);

关于C:结构用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45722432/

相关文章:

c - *++p 和++*p 指针的输出

c - 在 C 中使用压电传感器进行触摸输入手势配置文件

c - C 中的背靠背赋值

c - 读取映射文件并将其存储在缓冲区中

c++ - 谁能告诉我stream是c或c++中的保留关键字吗?

C 共享内存段故障

c++ 和 <complex.h> 与 <complex> 在单独的文件中

c - 如何从 char * 中过滤字母数字字符

c - realloc() 无效的旧大小

c - printf 中增量运算符的不明确行为