fgets 不会停止获取输入 C

  • 本文关键字:获取 fgets c
  • 更新时间 :
  • 英文 :


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

getInput调用存储从用户输入中获取的字符串的fgets,然后isInt检查它是否为int。问题是程序卡在了第一个CCD_ 7上。

int isInt (char* string)
{ 
int k=0;
while( string[k] != '')
{
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大小-堆栈溢出
  • fflush(stdin);调用未定义的行为,所以不应该使用它
  • 你必须在isInt的循环中增加k,否则它可能会陷入无限循环。(谢谢@Crowman(
#include <string> // for using strchr()
int isInt (char* string)
{ 
int k=0;
while( string[k] != '')
{
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 = ''; // 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))

最新更新