循环不适用于数字计数器

时间:2019-11-22 11:43:37

标签: c

所以我有这段代码,即使我输入了16位数字,它也会无限循环地返回,有人可以帮助我吗?

if (!strcmp(tropos,"card")){
    do{
        printf("dose noumero kartas me akrivos 16 psifia\n");
        scanf("%lld",&cardnum);
        no=cardnum;
        while(no!=0){
            no /= 10;
            ++totalDigits;
        }
    } while(totalDigits!=16);
}

1 个答案:

答案 0 :(得分:3)

do{
    totalDigits = 0; // you need to reset totalDigits every time you retry!
    printf("dose noumero kartas me akrivos 16 psifia\n");
    scanf("%lld",&cardnum);
    no=cardnum;
    while(no!=0){
        no /= 10;
        ++totalDigits;
    }
} while(totalDigits!=16);

如果前导零,则此解决方案存在问题。例如,0000123412341234仅计12位数字。我的建议是使用输入作为字符串来检查位数是否正确。