gpt4 book ai didi

c - 披萨代码不起作用 | Cinnamon 上的 C 编程

转载 作者:行者123 更新时间:2023-11-30 16:21:07 24 4
gpt4 key购买 nike

我正在尝试读取一个名字和一些答案,目标是让程序提出所有问题,提供必要的答案以及所有...

我想知道您是否可以帮助我了解问题出在哪里、为什么以及如何解决...

我在一台 Mint (Cinnamon) 机器上,使用终端通过 touch、nano 和 gcc 创建文件、编辑、编译和运行代码。

这是一个非常简单的代码,只是为了学习时的乐趣:

#include <stdio.h>
#include <stdlib.h>

int main () {

char answer, answer2, name;
int slices;

printf("Do you love Pizza? Please, enter your name:\n\n");
scanf("%c\n\n", &name);
printf("%c loves Pizza!!!\n\n", name);

printf("Are you all right, %c?\n\n", name);
scanf("%c\n\n", &answer);

printf("I am glad you are allright!! :D\n\n"); //it's supposed to be a positive answer!
printf("Do you want some slices now?\n\n");
scanf("%s\n\n", &answer2);

printf("Ah, that's awesome!!\n\n");
printf("And how many slices do you wish?\n\n");
printf("I want ");
scanf("%d\n\n", &slices);

printf("Awesome!!\n\n");
printf("Enjoy your %d Pizza slices!! :D\n\n", slices);
return 0;
}

1ˢᵗ 错误:仅打印输入信息的第一个字母

2ᶮᵈ错误:第二个问题和第四个问题根本没有完成,因此打印出 char 值(对吗?)

结果:

Do you love Pizza? Please, enter your name:

Finder
F loves Pizza!!!

Are you all right, F?

I am glad you are allright!! :D

Do you want some slices now?

YES
Ah, that's awesome!!

And how many slices do you wish?

I want Awesome!!

Enjoy your 29285 Pizza slices!! :D

如何解决这个问题?

最佳答案

每次向 scanf() 输入内容时,您始终需要清理 stdin 缓冲区以清除 '\n'。这就是为什么你的程序会跳过输入部分。

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // needed for strlen() function.

int main()
{
char name[50];
char answer, answer2;
int slices;
int c; // buffer cleaner.

printf("Do you love Pizza? Please, enter your name:\n\n");

if ((fgets(name, 50, stdin)) != NULL)// removing '\n' from the string.
{
size_t len = strlen(name);
if (len > 0 && name[len - 1] == '\n')
name[--len] = '\0';
}
printf("%s loves Pizza!!!\n\n", name);

printf("Are you all right, %s?\n\n", name);
getchar();
while ((c = getchar()) != '\n' && c != EOF) // cleaning the buffer
;
// scanf("%c\n\n", &answer);---> if it is suppossed to be positive answer why store the variable?

printf("I am glad you are allright!! :D\n\n"); //it's supposed to be a positive answer!
printf("Do you want some slices now?\n\n");
scanf("%c", &answer2); // Consider use only one char 'y' or 'n'. Else you have to use a fgets() and store in a string variable.
while ((c = getchar()) != '\n' && c != EOF) // cleaning the buffer
;
printf("Ah, that's awesome!!\n\n");
printf("And how many slices do you wish?\n\n");
printf("I want ");
scanf("%d", &slices);
while ((c = getchar()) != '\n' && c != EOF) // cleaning the buffer
;

printf("Awesome!!\n\n");
printf("Enjoy your %d Pizza slices!! :D\n\n", slices);
return 0;
}

关于c - 披萨代码不起作用 | Cinnamon 上的 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54992276/

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