2

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++) {
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Emre Turan
  • 83
  • 1
  • 8
  • 3
    I guess you use `scanf` before this code and the new line char will remain in the inputt buffer which your first `gets` will eat so the code will work as expected. Hard to say for sure tho without the whole code. – Eraklon Apr 21 '20 at 14:35
  • 6
    You cannot fix the problem with `gets()`. `gets()` is unfixable. –  Apr 21 '20 at 14:39
  • 6
    Welcome to StackOverflow! Please post the [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), the shortest complete code that shows the problem, and the exact input you are giving. Also please read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) You should be using `fgets` instead, `gets` is no longer a standard C function, and is only recognised by compilers for backward compatibility. – Weather Vane Apr 21 '20 at 14:39
  • Thank you for your comments. – Emre Turan Apr 21 '20 at 16:15

1 Answers1

0

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • I did use scanf() before gets() to take the value of 'choice'. I will try to use fgets and make it work. Thank you so much for your help. – Emre Turan Apr 21 '20 at 16:14