-1

Hi people in the coding community. I really need some help. How would you suggest that I add a Fgets function to this code? Thanks.

// 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;
}
Sasi V
  • 1,074
  • 9
  • 15
  • Reading [this question](https://stackoverflow.com/questions/58403537/what-can-i-use-for-input-conversion-instead-of-scanf/) might help. – Steve Summit Feb 02 '21 at 15:56

1 Answers1

0

You could replace both your scanf() functions with fgets() and 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;
}

Keep in mind, with fgets() you get a newline character in your buffer, you might want to strip it if you wish so.

alex01011
  • 1,670
  • 2
  • 5
  • 17