gpt4 book ai didi

c - 关于 C 中的结构

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:54 25 4
gpt4 key购买 nike

如果我尝试运行这段代码,它不会询问我 s2.name 的值。为什么会这样?

#include<stdio.h>

int main()
{
struct student
{
char name;
int roll;
int age;
};

struct student s1;
struct student s2;

printf("Enter name of the student: ");
scanf("%c", &s1.name);
printf("%c", s1.name);
printf("\n");

printf("Enter name of the student: ");
scanf("%c", &s2.name);
printf("%c", s2.name);

return 0;
}

最佳答案

当您输入单个字符并按下 Enter 键时,您实际上输入了 两个 个字符:输入中的字符和 Enter 中的换行符 键。

第二个 scanf 读取这个换行符。

或者,如果您将多个字符作为名字的输入,那么第二个字符将由第二个 scanf 读取。


解决第一个问题的方法很简单:告诉 scanf 读取并丢弃 leading 空白(即换行符),方法是在格式,例如

scanf(" %c", &s2.name);
// ^
// Note space here

解决第二个问题的方法是改为读取strings,这意味着你必须将你的name成员变成数组,然后使用"% s" 格式(最好具有指定的宽度,这样您就不会读到很多字符)。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com