I've just wrote this program and when i compile, the gets() function is skip before i can enter the string. i have try cin.getline but the same problem occurs. Can anybody tells me what's the problem and to solve it?
Hi,
The problem is that we need to clear the input buffer before using gets() because gets() read anything in the input buffer until it encounters a new line or return character. Although it works correctly, it is unsafe to use gets() if the input is bigger than the array can be stored, it writes over the array as we are not expected. Good luck with your program.
Here is the modified code:
#include<iostream>
#include<cctype>
using namespace std;
int main ()
{ char str[10]="ABCDE FG", ch, solve[10], guess[10];
int select;
Using fgets, the newline may be retained in the string -- it then becomes part of the comparison. If you don't want the newline at the end of the string, remove it.
size_t end = strlen(solve) - 1; /* find position of last character */
if(solve[end] == '\n')/* see if it is a newline */
{
solve[end] = '\0'; /* get rid of the newline */
}
}
Quote originally posted by lara_ ...
about fflush(stdin), if didn't use this function then is there any other function can replace?
First, learn to use fgets correctly. Or else realize that it was the leftover character(s) that was causing problems. Reading leftover characters up to and including a newline can be done a variety of ways. Here are a few.
type it twice, for example :
char variable[100];
gets(variable);
gets(variable);
it'll work.
edit :
sorry, you have asked why. im sorry i dont know why, all i can do to help is above :/
Last edited by member19; Dec 18th, 2008 at 2:44 pm.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
This thread is currently closed and is not accepting any new replies.