Remilia Scarlet
Remilia Scarlet

Reputation: 33

Why is my code ignoring my fgets() and giving it a 0 value?

There is buffer overflow causing fgets to get a new line without taking in any stdin from the user. If I use a function to clear the buffer before stringswap() is used the program runs fine and I am able to change the value of the string and have it printed. However I want to know where the buffer overflow originates from to not have this happen again.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

char arg[100];

void Options();
int AskChoice();
void stringswap();
void clear();

int main()
{
    Options();
    return 0;
}

void Options()
{
    int choice = 0;
    choice = AskChoice();
    if (choice == 1) {
        stringswap(arg);
        printf("Your word is %s\n", arg);
        Options();
    }
    else if (choice == 2) {
        printf("Goodbye");
    }
    else {
        Options();
    }
}

int AskChoice()
{
    int choice = 0;
    char Choice[2];
    printf("Enter 1 to say a word, enter 2 to exit program.\n");
    fgets(Choice, 2, stdin);
    choice = atoi(Choice);
    printf("Your choice is %d\n", choice);
    return choice;
}

void stringswap(char* input)
{
    printf("Enter a new string");
    fgets(input, 50, stdin);
}

void clear()
{
    while (getchar() != '\n')
        ;
}

I expect to type in a word and get it repeated back to me, but instead it's completely ignored and I get a blank space returned back.

Upvotes: 0

Views: 399

Answers (1)

chux
chux

Reputation: 153457

2 is enough to get 1 char and then append a null character. Thus only consuming 1 character from the user per call. No enough per OP's needs.

Use a larger buffer.

// char Choice[2];
char Choice[100];
printf("Enter 1 to say a word, enter 2 to exit program.\n");
// fgets(Choice, 2, stdin);
fgets(Choice, sizeof Choice, stdin);

Upvotes: 1

Related Questions