您的代码有一些小问题。这里是一个更好的办法来做到这一点(未经测试):
bool validate_int(char input[]) /* Bad function name; See @Filipe's comment */
{
for(;;) /* Infinite loop */
{
if(fgets(input, 10, stdin) == NULL) /* If fgets failed */
{
puts("fgets failed");
return false;
}
int i, len = strlen(input);
if(len > 0 && input[len - 1] == '\n') /* If there is a newline character at the end of input */
input[--len] = '\0'; /* Replace the '\n' with '\0' and decrement len */
if(!isalpha(input[0])) /* If the first character of input is not an alphabet */
continue; /* Loop again */
if(len == 1) /* There is no number */
continue;
for(i = 1; i < len; ++i)
{
if(!isdigit(input[i])) /* If not a digit */
continue; /* Loop again */
}
break; /* Get out of the loop */
}
return true;
}
更更好的方式是独立的输入和验证分为两个独立的功能(未经测试):
bool getInput(char input[])
{
if(fgets(input, 10, stdin) == NULL) /* If fgets failed */
{
puts("fgets failed");
return false;
}
int len = strlen(input);
if(len > 0 && input[len - 1] == '\n') /* If there is a newline character at the end of input */
input[--len] = '\0'; /* Replace the '\n' with '\0' and decrement len */
return true;
}
bool validate(char input[])
{
if(!isalpha(input[0])) /* If the first character of input is not an alphabet */
return false;
int i, len = strlen(input);
if(len == 1) /* There is no number after the character */
return false;
for(i = 1; i < len; ++i)
{
if(!isdigit(input[i])) /* If not a digit */
return false;
}
return true;
}
和在调用功能(再次,未经测试),
char input[10];
if(getInput(input))
{
if(validate(input))
{
puts("Input is in correct format");
}
else
{
puts("Input is in wrong format");
}
}
else
{
puts("Failed to get input");
}
你绝不能忽略的输入操作的返回值。你的方法被打破,无法修复。 –
@KerrekSB呃......只有在错误检查是需求的情况下。我听到人们说了很多,但严重的是,这可能是一个用于学习字符串操作的小型玩具程序,而不是用于了解处理I/O错误的学习。 – immibis
我只想检查从索引1开始的数组元素是不是其他类型的整数。 –