-1

嗨,编码社区的人们。我真的需要一些帮助。您如何建议我在此代码中添加 Fgets 函数?谢谢。

// I decided to make a storyboard. If you don't know what that is, It's a story that let's you makes choices, and changes based on your choices.
    
#include <stdio.h>

int main(void) 
{
    char characterName[100];
    int aa;
    printf("Hello. This code will write a story, based on your choice.\n");
    printf("What is the name of your character?\n");
    scanf("%s",characterName);
    printf("Your name is %s",characterName);
    printf("\n");
    printf("One day, while walking through a forest, you encounter a mysterious, entrancing portal. Do you enter it %s", characterName);
    printf("?\n");
    printf("Enter Number 1 to Stay, Number 2 for Entering it.\n");
    scanf("%i",&aa);
    if (aa == 1)
    {
        printf("You chose to stay. END OF STORY.");
    }
    else if (aa == 2)  
    {
        printf("You step towards the bright, purple portal.\n It looks like a swirly mirror. You are entranced as you step forward, step after step. Adventures await you.");
    }
    return 0;
}
4

1 回答 1

0

你可以用和替换你的scanf()函数。fgets()sscanf()

#include <stdio.h>

#define MAX_SIZE 100

int main(void)
{
    int n = 0;
    char characterName[MAX_SIZE];
    char number[MAX_SIZE];

    printf("Hello. This code will write a story, based on your choice.\n");
    printf("What is the name of your character?\n");

    fgets(characterName, MAX_SIZE, stdin);

    printf("Your name is %s", characterName);
    printf("One day, while walking through a forest, you encounter a mysterious, entrancing portal. Do you enter it %s", characterName);
    printf("Enter Number 1 to Stay, Number 2 for Entering it.\n");

    fgets(number, MAX_SIZE, stdin);
    if (sscanf(number, "%i", &n) !=1 )
    {
        /* error handling */
        return -1;
    }

    if (n == 1)
    {
        printf("You chose to stay. END OF STORY.");
    }
    else if (n == 2)
    {
        printf("You step towards the bright, purple portal.\n It looks like a swirly mirror."
                "You are entranced as you step forward, step after step. Adventures await you.");
    }
    return 0;
}

请记住,当fgets()您在缓冲区中获得一个newline字符时,如果您愿意,您可能希望删除它。

于 2021-02-02T15:47:09.577 回答