gpt4 book ai didi

c - 处理用户在 C 中输入的字符串(错误处理)

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

好的,所以我正在构建一个程序,它询问用户半金字塔应该有多高,然后用户输入一个范围为 1-24 的整数(如果他们输入超出此范围的整数,我有一个 do while 循环).

然后程序继续构建半金字塔。我的问题是,如果用户输入一个字符或字符串,基本上任何不是数字的东西,程序都会崩溃,我搜索了所有地方,但仍然找不到适用于我的情况的解决方案。

这是我的代码:

#include <stdio.h>

main()
{
int height; //user inputs this
int counter;
int line;

do
{
printf("What height should the half pyramid be?\n");
scanf("%d", &height);

printf("You typed in %d\n", height);

if(height > 23 || height<1)
{
printf("The half pyramid must be no bigger than 23 and higher than 0 buddy\n");
}
}
while(height >23 || height<1);

for(line = 1; line <= height; line++)
{
int spaceNum = height - line;
int spaceCounter;

for (spaceCounter = 0; spaceCounter <= spaceNum ; spaceCounter++)
printf(" ");

for(counter = 0; counter < line ; counter++)
printf("#");

printf("\n");
}

return 0;
}

最佳答案

读入一个字符串并使用 sscanf 解析该字符串。检查 sscanf 返回值,了解从中成功读取了多少字段。

关于c - 处理用户在 C 中输入的字符串(错误处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569983/

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