简体   繁体   English

fgets 不会停止获取输入 C

[英]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!问题是我使用fgets获取输入,但是当被调用时,它不会停止从用户那里获取输入! I tried to fix adding fflush(stdin) and fflush(stdout) to fix because I read some stuffs online but isn't working :S我试图修复添加fflush(stdin)fflush(stdout)来修复,因为我在网上阅读了一些东西但不起作用:S

getInput calls the fgets that stores the string taken from user input then isInt checks if it's an int or not. getInput调用存储从用户输入中获取的字符串的fgets ,然后isInt检查它是否为 int。 The problem is that the program stucks on the first fgets .问题是程序卡在第一个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. fgets()将从流中读取的换行符放入数组,因此删除它以避免isInt返回1看到换行符。
  • sizeof(string) is the size of pointer, not the size of pointed buffer. sizeof(string)是指针的大小,而不是指向缓冲区的大小。 You will have to receive the size of buffer separately.您必须单独接收缓冲区的大小。 For more information, see C sizeof a passed array - Stack Overflow .有关更多信息,请参阅C sizeof 传递的数组 - 堆栈内存溢出
  • fflush(stdin); invokes undefined behavior , so you shouldn't use that.调用undefined behavior ,所以你不应该使用它。
  • You have to increment k in the loop in isInt , or it may stuck into an infinite loop.您必须在isInt的循环中增加k ,否则它可能会陷入无限循环。 (thanks @Crowman) (感谢@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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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