gpt4 book ai didi

c - scanf 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:06 26 4
gpt4 key购买 nike

试图为结构获取一些值。当我运行代码时,除了 Gender 值外,一切都完美无缺。由于某种原因,整个 scanf 被跳过。在命令提示符下它看起来像这样。

请提供学生的名字:(用户输入“John”并按回车键)

请提供学生的名字:(用户输入“Doe”并按回车键)

请提供学生的性别(男/女):(不能输入任何内容,不能跳行)请提供学生的年龄:(输入)

等等

我不知道这是否是程序另一部分的问题,但如果问题不在这段代码中,我可以对整个内容进行编辑。

if (option == 2){
i=i+1;
printf("Please provide the student's first name: ");
scanf("%s", roster[i].firstname);
printf("Please provide the student's last name: ");
scanf("%s", roster[i].lastname);
printf("Please provide the student's gender (M/F): ");
scanf("%c", &roster[i].gender);
printf("Please provide the student's age: ");
scanf("%i", &roster[i].age);
printf("Please provide the student's weight (In pounds): ");
scanf("%i", &roster[i].weight);
printf("Please provide the student's height (In inches): ");
scanf("%i", &roster[i].height);
}

最佳答案

这里的问题是读取姓氏的代码读取到但不包括输入末尾的换行符,并且 %c 转换规范不会跳过前导空格,因此性别输入将换行符读入性别并继续到下一个提示(年龄)。

在读取非空格字符之前,使用 "%c" 跳过空格(包括空格、制表符和换行符)。

顺便提一下,您应该检查每个 scanf() 调用以确保它识别输入。

printf("Please provide the student's first name: ");
if (scanf("%s", roster[i].firstname) != 1)
...handle error...
printf("Please provide the student's last name: ");
if (scanf("%s", roster[i].lastname) != 1)
...handle error...
printf("Please provide the student's gender (M/F): ");
if (scanf("%c", &roster[i].gender) != 1)
...handle error...
printf("Please provide the student's age: ");
if (scanf("%i", &roster[i].age) != 1)
...handle error...
printf("Please provide the student's weight (In pounds): ");
if (scanf("%i", &roster[i].weight) != 1)
...handle error...
printf("Please provide the student's height (In inches): ");
if (scanf("%i", &roster[i].height) != 1)
...handle error...

此外,对姓氏甚至名字中有空格的学生表示遗憾。

关于c - scanf 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20436139/

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