如何正确读取整数?

时间:2017-03-27 07:30:57

标签: c fgets getchar

我的程序测试一个数字是否是两个函数的正整数。但是当我输入一个像5.4这样的实数时,行c=getchar()不会等待我的输入。

int main() {
        int num;
        char c = 'y';
        printf("\n\n");
        do{ 
            printf("**********************************************\n");
            printf("Enter a positive integer to test: ");
            scanf("%d",&num);
            getchar();
            if(num<0) {
                printf("cannot accept a negative integer.\n");
            }   
            else
                is_power_of_two(num);
            printf("Do you want to try again?\nEnter 'y' if yes, else press any other key to exit: ");
            c = getchar();
            printf("**********************************************\n");
        }while(c=='y');
        return 0;
    }

输出:

Enter a positive number to test: 8
Yes it is a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: y
**********************************************
**********************************************
Enter a positive number to test: 7.6
No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: **********************************************

我尝试过使用fgets和atoi而不是scanf和getchar(),如下所示。但是fgets在第二次迭代期间并没有等待。我尝试在每次迭代中清除麻木。但没有区别。 getchar()是否也像scanf一样在缓冲区中留下\ n?

这里发生了什么,是否有一种简单的方法或正确的方法来读取整数而不会造成很多麻烦?

int main() {
    char numbuf[10];
    int num;
    char c = 'y';
    printf("\n\n");
    do{ 
        printf("**********************************************\n");
        printf("Enter a positive number to test: ");
        fgets(numbuf, sizeof(numbuf),stdin);
        num = atoi(numbuf);
        if(num<0) {
            printf("cannot accept a negative integer.\n");
        }   
        else
            is_power_of_two(num);
        printf("Do you want to try again?\nEnter 'y' if yes, else press any other key to exit: ");
        c = getchar();
        printf("**********************************************\n");
    }while(c=='y');
    return 0;
}

输出:

**********************************************
Enter a positive number to test: 9
No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit: y
**********************************************
**********************************************
Enter a positive number to test: No it is not a power of 2
Do you want to try again?
Enter 'y' if yes, else press any other key to exit:

1 个答案:

答案 0 :(得分:1)

我调试了你的代码并看到了一个有趣的东西:当你输入一个漂浮的数字,如5.4时,5保存在num中,4仍然存在,所以当它被要求输入一个&#39; y&#39;或按任意键,&#39; 4&#39;扫描,程序终止。 看图(我输入了5.4) here is the locals

我认为如果你将num定义为float的类型,你的问题就会得到解决。

相关问题