它必须是一个不大于 23 的非负整数......没有空白条目或其他条目,如果是这样,它会再次重新提示用户 我有
int main(void){
int rows;
while (rows < 1 || rows > 23)
{
printf("Height:");
scanf("%d", &rows);
}
那么我不知道该为对方做什么。
它是NULL吗?哦什么哈哈 我将如何实现
最佳答案
避免undefined behavior通过初始化rows
(如果你运气不好的话,它的未定义初始垃圾值可能是18)....
使用 getline(3) 读取整行否则fgets(3) .
然后使用 sscanf(3) 解析该行(考虑 sscanf
的结果,也许使用 %n
)或使用 strtol(3) (例如,声明 char *end=NULL;
后的 long n=strtol(p,0,&end);
)
或者至少,使用 scanf
的结果,例如
int rows = 0;
while(1) {
puts("number of rows?");
fflush(stdout);
int nbscan = scanf("%d", &rows);
if (nbscan<=0) continue;
if (rows < 1 || rows>20) continue;
if (feof(stdin)) break;
}
关于c - 在 'C' 我如何 - 检查用户输入的 int 以及是否会重新提示用户字母、字符或空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21221818/