简体   繁体   中英

How can I fix the problem with gets() function in C?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM