繁体   English   中英

fgets 不会停止获取输入 C

[英]fgets doesn't stop getting input C

我创建了一个函数来检查给定的字符串是否为数字。 问题是我使用fgets获取输入,但是当被调用时,它不会停止从用户那里获取输入! 我试图修复添加fflush(stdin)fflush(stdout)来修复,因为我在网上阅读了一些东西但不起作用:S

getInput调用存储从用户输入中获取的字符串的fgets ,然后isInt检查它是否为 int。 问题是程序卡在第一个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()将从流中读取的换行符放入数组,因此删除它以避免isInt返回1看到换行符。
  • sizeof(string)是指针的大小,而不是指向缓冲区的大小。 您必须单独接收缓冲区的大小。 有关更多信息,请参阅C sizeof 传递的数组 - 堆栈内存溢出
  • fflush(stdin); 调用undefined behavior ,所以你不应该使用它。
  • 您必须在isInt的循环中增加k ,否则它可能会陷入无限循环。 (感谢@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