gpt4 book ai didi

c - 输入无效输入时无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:12 26 4
gpt4 key购买 nike

我是 C 编程的新手,我想检查我的所有数组元素都是整数,除了第一个元素。

我写了下面的代码,但是一旦我插入错误的输入,循环就不会停止。

bool validate_int(char input[]){
fgets(input,10, stdin);
for(int i = 1; i < strlen(input); ++i) {
if(!isdigit(input[i])){
i = 1;
fgets(input,10, stdin);
}
else{
}
}
return true;
}

最佳答案

您的代码有一些小问题。这是一个更好的方法(未经测试):

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");
}

关于c - 输入无效输入时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32797489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com