There is a problem with gets
function. The first gets
I write does not work but the ones comes next works properly.
I put an extra gets()
function at the beginning, program just skips it and gets the string I want. But it is not safe and reliable. So what is the problem with gets and how can I fix it?
if (choice == 1) {
printf("Please enter an English phrase with upper case: ");
gets(a);
gets(engphr);
for (i = 0; engphr[i] != '\0'; i++) {
As Eraklon mentions in their comment, the most likely cause is that you have a scanf
call before the gets
call, and the trailing newline from the previous input is getting consumed by gets
before you have a chance to enter anything else.
You should never use gets
anyway - it was removed from the standard library in the 2011 version of the language. It is inherently unsafe to use, and will introduce a security hole in your code. Use fgets
instead. Its behavior is slightly different (it will save the trailing newline to the input buffer if there's room, where gets
discarded it), but it's much safer:
if ( fgets( engphr, sizeof engphr, stdin ) ) // assumes engphr is declared as an array, not a pointer
{
// process engphr
}
Having said that, you really shouldn't mix calls to scanf
and fgets
, again because scanf
will leave trailing newlines in the input stream from previous inputs, and fgets
will immediately return after seeing that newline. Either read all input using fgets
and use sscanf
to read specific items from the input buffer, or read all input with scanf
.