函数中的 gets() 在第二次使用后被跳过

gets() in function gets skipped after second use

本文关键字:第二次 gets 函数      更新时间:2023-10-16

我正在尝试制作一个文本输入函数,如下所示InputText函数:

char* InputText(char Dummy[256])
{
    gets(Dummy);
    return Dummy;
}

但是当再次调用该函数时,gets(Dummy)被跳过。我已经通过StackOverflow(通过使用cin.ignore()cin.clear())研究了这个问题,但我似乎找不到正确的答案和解释。

这是我对该函数的程序:

#define pr_ cout<<
#define in_ cin>>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char* InputText(char Dummy[256]);
main()
{
    char Quest;
    do
    {
        char InputChar[256];
        int InputLength;
        pr_ "n Input text (Note: press Enter twice to finish input.)n >";
        InputText(InputChar);
        InputLength=strlen(InputChar);
        pr_ "n You inputted : "<<InputChar;
        pr_ "n String length: "<<InputLength;
        do
        {
            pr_ "nn Restart program?n >";
            in_ Quest;
            if(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N')
            pr_ " System error: not an answer.";
        }
        while(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N');
    }
    while(Quest=='y' || Quest=='Y');
}
char* InputText(char Dummy[256])
{
    gets(Dummy);
    return Dummy;
}

这是程序输出的示例,以及我提到的问题:

Input text (Note: press Enter twice to finish input.)
>I am Groot!
You inputted : I am Groot!
String length: 11
Restart program?
>y
Input text (Note: press Enter twice to finish input.)
>
You inputted :
String length: 0
Restart program?
>

所以我的问题:如何使gets()部分不被跳过?对不起,如果我再次问这个问题。

更新1:从R Sahu的回答来看,我现在正在使用fgets()。但它仍然被跳过了。

使用

    do
    {
        pr_ "nn Restart program?n >";
        in_ Quest;
        cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        if(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N')
        pr_ " System error: not an answer.";
    }

为我工作。

告诫:

请不要使用gets。它是安全问题的根源。请改用fgets。请参阅为什么 get 函数如此危险以至于不应使用它?。