我创建了一个函数,用于检查给定字符串是否为数字。问题是,我用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))