scanf跳过

Aus*_*vis 8 c scanf

我正在尝试为一个类创建一个简单的C程序,其中一个要求是我需要使用scanf/ printf用于所有输入和输出.我的问题是为什么我scanf跳过主循环中的for循环并且程序刚终止.

这是我的代码

#include <stdio.h>

void main() {
    int userValue;
    int x;
    char c;

    printf("Enter a number : ");
    scanf("%d", &userValue);
    printf("The odd prime values are:\n");
    for (x = 3; x <= userValue; x = x + 2) {
        int a;
        a = isPrime(x);
        if (a = 1) { 
            printf("%d is an odd prime\n", x);
        }
    }   
    printf("hit anything to terminate...");
    scanf("%c", &c);    
}

int isPrime(int number) {
    int i;
    for (i = 2; i < number; i++) {
        if (number % i == 0 && i != number)
            return 0;
    }
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

我能够通过scanf在第一个之后添加另一个相同来"修复"它,但我更愿意使用它.

hmj*_*mjd 20

输入stdin上一个之后出现的新行字符int将不会被最后一次调用消耗掉scanf().因此,循环scanf()之后的调用for会消耗换行符,并且在用户不必输入任何内容的情况下继续.

要纠正,而无需添加其他scanf()电话可以使用格式说明" %c"scanf()for循环.这将使scanf()跳过任何前导空格字符(包括换行符).请注意,这意味着用户必须输入除换行之外的其他内容才能结束该程序.

另外:

  • @SSHThis,`scanf("%d")`在遇到非数字的东西时停止消耗,而换行不是数字,所以它将保留. (2认同)