披萨代码没有工作| C肉桂编程

问题描述 投票:0回答:1

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

我想知道你是否可以帮我理解什么是错的,为什么以及如何解决它...

我在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

如何解决这个问题?

c char int printf scanf
1个回答
0
投票

每当你向stdin输入东西以摆脱scanf()时,你总是需要清理'\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;
}
© www.soinside.com 2019 - 2024. All rights reserved.