![](/img/trans.png)
[英]C - Why is a for loop getting stuck when using a uint64_t counter, whereas a while loop isn't?
[英]counter getting reset in while loop in C
我是编程新手,并使用 while 循环在无符号字符数组中输入 integer 输入。 不知何故,计数器正在自动重置,从而使 while 无限循环 go。
int i;
unsigned char ab[7];
printf("Enter numbers : ");
i=0;
while(i<7)
{
scanf(" %d",&ab[i]);
fflush(stdin);
i++;
printf("\nvalue of i : %d",i);
}
通过打印计数器值,我知道计数器正在重置。
你能建议出了什么问题,为什么? 我能做些什么来使它正确?
我正在使用下面的 gcc 版本详细信息对其进行编译。
苹果 clang 版本 13.1.6 (clang-1316.0.21.2.5)
目标:x86_64-apple-darwin21.6.0
线程 model:posix
谢谢
使用scanf()
%d 用于 int*,但 %hhu 假定为 unsigned char*。
我还清理了printf()
,并将 fflush(stdin) 更改为 stdout,因为它对 stdin 没有意义。
#include <stdio.h>
int main () {
int i;
unsigned char ab[7];
printf("Enter numbers : ");
i=0;
while(i<7)
{
scanf("%hhu", &ab[i]);
i++;
printf("value of i : %d\n",i);
fflush(stdout);
}
}
这有效:
% counter
Enter numbers : 1
value of i : 1
2
value of i : 2
3
value of i : 3
4
value of i : 4
5
value of i : 5
6
value of i : 6
7
value of i : 7
%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.