您的代碼有一些小問題。這裏是一個更好的辦法來做到這一點(未經測試):
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開始的數組元素是不是其他類型的整數。 –