简体   繁体   中英

fgets doesn't stop getting input C

I created a function that checks if a given string is a number or not. The problem is that I take the input with fgets but ,when called, it doesn't stop to take input from user! I tried to fix adding fflush(stdin) and fflush(stdout) to fix because I read some stuffs online but isn't working :S

getInput calls the fgets that stores the string taken from user input then isInt checks if it's an int or not. The problem is that the program stucks on the first fgets .

int isInt (char* string)
{ 
  int k=0;
  while( string[k] != '\0')
  {
    if ( isdigit(string[k])==0) //it's k++ here, I copied bad
      return 1;
  }
  return 0;
}

void getInput(char* string)
{
    printf("Insert a number : \n");
    while (1)
    {
       fflush(stdout); //Tried to fix
       fflush(stdin); //same as above
       fgets(string,sizeof(string),stdin); //stucks here
        if(isInt(string)==0 )
        {
            printf("Ok it's a number!\n");
            break;
        }
        else printf("Insert a valid number!\n");;
    }
}
  • fgets() will put newline character read from the stream into the array, so remove that to avoid isInt returning 1 seeing the newline character.
  • sizeof(string) is the size of pointer, not the size of pointed buffer. You will have to receive the size of buffer separately. For more information, see C sizeof a passed array - Stack Overflow .
  • fflush(stdin); invokes undefined behavior , so you shouldn't use that.
  • You have to increment k in the loop in isInt , or it may stuck into an infinite loop. (thanks @Crowman)
#include <string> // for using strchr()

int isInt (char* string)
{ 
  int k=0;
  while( string[k] != '\0')
  {
    if ( isdigit(string[k])==0)
      return 1;
    k++; // increment k
  }
  return 0;
}

void getInput(char* string, size_t string_max) // add parameter to get buffer size
{
    printf("Insert a number : \n");
    while (1)
    {
       fflush(stdout);
       fgets(string,string_max,stdin); // use passed buffer size instead of sizeof()
       char* lf = strchr(string, '\n'); // find newline character
       if (lf != NULL) *lf = '\0'; // and remove that if it exists
        if(isInt(string)==0 )
        {
            printf("Ok it's a number!\n");
            break;
        }
        else printf("Insert a valid number!\n");
    }
}

我认为你应该把 fgets 放在 while 条件中:

while(fgets(string,sizeof(string),stdin))

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