I'm trying to make a text input function, like this InputText
function below:
char* InputText(char Dummy[256])
{
gets(Dummy);
return Dummy;
}
But when the function is called again, gets(Dummy)
get skipped. I have researched this problem through StackOverflow (by using cin.ignore()
or cin.clear()
) and I can't seem to find the right answer and explanation.
Here's my program for the function:
#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;
}
Here's the example of the program output, with the problem I mentioned:
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?
>
So my question: How do I make the gets()
part not getting skipped? Sorry if I re-asked this question.
UPDATE 1: From R Sahu's answer, I am now using fgets()
. But it's still skipped.
Using
works for me.
Words of caution:
Please don't use
gets
. It is a source of security problems. Usefgets
instead. See Why is the gets function so dangerous that it should not be used?.