gpt4 book ai didi

c - 在没有数组的情况下读取整数和/或字符

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

我需要一个一个地读取一个整数,直到读取到一个'$',然后判断最大,最小等等。我可以使用字符变量并执行它,但它适用于从 0 到 9 的数字。但是我如何读取两位或更多位的整数并同时检测 '$' - 我使用了 char *,但我猜它相当于一个数组,我不应该在这里使用它。此外,char 包含单个数字/char,因此不适合更大的数字。我该怎么办?

最佳答案

没有数组,没有指针,没有棘手的逐字符读取和转换。只是简单的 scanfgetchar

#include <stdio.h>

int main()
{
int newValue=0; /* value being acquired */
int max; /* current maximum value */
int min; /* current minimum value */
int firstAcquired=0; /* boolean flag set to 1 after first acquisition */
int ch; /* used as temporary storage for the getchar() */
for(;;)
{
/* scanf returns the number of successfully acquired fields; here if it
returns 0 means that the value couldn't be acquired */
if(scanf("%d",&newValue)==0)
{
/* scanf failed, but it's guaranteed it put the offending character
back into the stream, from where we can get it */
ch=getchar();
if(ch=='$' || ch==EOF)
break;
else
/* from here to the break it's just to handle invalid input and EOF
gracefully; if you are not interested you can replace this stuff
with a random curse to the user */
{
puts("Invalid input, retry.");
/* Empty the buffer */
while((ch=getchar())!='\n' && ch!=EOF)
;
}
/* if it's EOF we exit */
if(ch==EOF)
break;
}
else
{
/* Everything went better than expected */
if(!firstAcquired || newValue>max)
max=newValue;
if(!firstAcquired || newValue<min)
min=newValue;
firstAcquired=1;
}
}
if(firstAcquired)
{
printf("The maximum value was %d\n", max);
printf("The minimum value was %d\n", min);
}
return 0;
}

关于c - 在没有数组的情况下读取整数和/或字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7661856/

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