gpt4 book ai didi

c - 处理错误,无限循环

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

这会在输入高度时创建一个类似马里奥的金字塔。

#include <stdio.h>

int main(void)
{
int height;
char signal = 'n';

while (signal != 'y')
{
printf("Height: ");
scanf("%d", &height);

if (height <= 0)
{
printf("Error. Positive #s only. \n");
}
else if (height > 23)
{
printf("Error. # must be from 0-23. \n");
}
else if (height > 0 || height <= 23)
{
signal = 'y';
}
else
{
printf("Can you bulid a pyramid with letters? I thought so... \n");
}
}

int i, j, k;

for (i = 1; i <= height; i++)
{
if (height <= 8)
printf("\t");
else if (height <= 16)
printf("\t\t");
else if (height <= 23)
printf("\t\t\t");

for (k = 0; k < i; k++)
{
printf("\b");
}

for (j = 0; j <= i; j++)
{
printf("#");
}
printf("\n");
}
}

如果用户决定犯傻并输入字符串,程序将进入无限循环。我以为程序会使用 else 语句但没有。我该如何处理?

最佳答案

需要检查scanf的返回值,返回匹配分配的输入项的个数。如果您输入文本,它不会匹配任何内容,文本将留在输入缓冲区中。所以 scanf 在循环的每次迭代中不断尝试读取相同的不匹配数据。

通过检查返回值,您可以判断是否输入了字符串。您还需要通过调用 getchar 清除输入缓冲区,直到获得换行符。

试试这个:

  int items = scanf("%d", &height);

if (items < 1) {
int ch;
printf("Please enter a number\n");
while (((ch=getchar()) != '\n') && (ch != EOF));
else if(height <= 0)
...

关于c - 处理错误,无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180726/

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