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

时间:2014-11-29 05:21:21

标签: c++ cin getline gets

我正在尝试创建一个文本输入函数,如下面的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_ "\n\n 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()。但它仍然被忽略了。

1 个答案:

答案 0 :(得分:0)

使用

    do
    {
        pr_ "\n\n 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。请参阅Why is the gets function so dangerous that it should not be used?