简体   繁体   English

计数器在 C 的 while 循环中重置

[英]counter getting reset in while loop in C

I am a newbie in programming and taking integer inputs in unsigned character array, using while loop.我是编程新手,并使用 while 循环在无符号字符数组中输入 integer 输入。 Somehow the counter is getting auto reset thus making while loop go infinitely.不知何故,计数器正在自动重置,从而使 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);
}

By printing counter value, I got to know that counter is getting reset.通过打印计数器值,我知道计数器正在重置。

Can you suggest what is going wrong and why?你能建议出了什么问题,为什么? And what I can do to make it right?我能做些什么来使它正确?

I am compiling it using gcc version details below.我正在使用下面的 gcc 版本详细信息对其进行编译。

Apple clang version 13.1.6 (clang-1316.0.21.2.5)苹果 clang 版本 13.1.6 (clang-1316.0.21.2.5)
Target: x86_64-apple-darwin21.6.0目标:x86_64-apple-darwin21.6.0
Thread model: posix线程 model:posix

Thanks谢谢

With scanf() %d is for int*, but %hhu assumes unsigned char*.使用scanf() %d 用于 int*,但 %hhu 假定为 unsigned char*。

I also cleaned up the printf() , and changed the fflush(stdin) to stdout as it makes no sense for stdin.我还清理了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);
        }

}

This works:这有效:

% 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM