为什么我的代码忽略了我的fgets()并给它一个0值?

时间:2019-02-01 01:00:10

标签: c

缓冲区溢出导致fgets换行而不用用户输入的任何stdin。如果我在使用stringswap()之前使用函数清除缓冲区,则程序可以正常运行,并且能够更改字符串的值并将其打印出来。但是我想知道缓冲区溢出来自何处,而不会再次发生这种情况。

#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')
        ;
}

我希望输入一个单词并将其重复返回给我,但是相反,它被完全忽略了,并且我得到了一个空格。

1 个答案:

答案 0 :(得分:1)

2足以得到1 char,然后附加一个空字符。因此,每个呼叫仅消耗用户一个字符。每个OP的需求不足。

使用更大的缓冲区。

// 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);