【发布时间】:2015-10-19 02:58:16
【问题描述】:
我有一个程序来检查用户输入并确保它只是整数而不是字符。在我的main 函数中,do while 循环仅在输入不正确时执行一次。但我希望它保持执行,直到用户输入有效输入。我的 doAgain() 函数是询问用户是否要再试一次。 问题在于 doAgain() 函数。如果将它留在if 语句中,它只会执行一次。除此故障外,一切正常。但是,当我删除它时,循环会继续执行,直到用户输入我想要的有效输入,但是 doAgain() 函数将无用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* 获取边界 */
char* getBoundary(char str[]){
int i;
char c;
str = (char*) malloc(sizeof(char));
for (i = 0; (c = getchar()) != '\n'; i++) // The loop stop running after the second time
{
str = (char *) realloc(str, sizeof(char) + i);
str[i] = c;
}
str[i] = '\0';
return str;
}
/* 检查有效字符串 */
int checkStr(const char *check)
{
unsigned i;
size_t len = strlen(check);
for (i = 0; i < len; i++)
if(isalpha(check[i]))
{
printf("Invalid integer formatt!!!");
return 0;
}
return 1;
}
/* 询问是否再做 */
int doAgain(void)
{
char ans, c;
do {
printf("Do you want to try again?: ");
scanf(" %c", &ans);
switch (ans)
{
case 'y':
case 'Y':
case 'n':
case 'N':
return (ans == 'y') || (ans == 'Y') ? 1 : 0;
break;
default:
printf("Invalid answer!!! answer 'y' and 'Y' or 'n' and 'N' only\n");
do { /* flush input stream */
c = getchar();
}while (c != '\n');
}
}while (1);
}
/* 主要 */
int main(void)
{
char *l_boundRow;
l_boundRow = NULL;
do {
printf("Enter lower bound row: ");
l_boundRow = getBoundary(l_boundRow);
if (!checkStr(l_boundRow) && doAgain()) // problem start here, it works if I remove doAgain() function
continue; // if the string is invalid, the program asks user if they want to try again
else
break;
}while (1);
free(l_boundRow);
return 0;
}
【问题讨论】:
-
返回后的break是不可达代码。您可以通过在
case 'y': case 'Y':之后执行return 1;和在case 'n': case 'N':之后执行return 0;来简化代码。但是,这两点都与您当前的问题无关。 -
编译所有警告和调试信息 (
gcc -Wall -Wextra -g) 然后使用调试器 (gdb)
标签: c