Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中scanf()的机制是什么_C_Visual Studio_Loops_Scanf - Fatal编程技术网

C中scanf()的机制是什么

C中scanf()的机制是什么,c,visual-studio,loops,scanf,C,Visual Studio,Loops,Scanf,所以我今天开始学习C,作为练习,我被告知编写一个程序,要求用户输入数字,直到他们输入0,然后将偶数和奇数相加。这是: #include <stdio.h>; int main() { int esum = 0, osum = 0; int n, mod; puts("Please enter some numbers, 0 to terminate:"); scanf("%d", &n); while (n != 0) {

所以我今天开始学习C,作为练习,我被告知编写一个程序,要求用户输入数字,直到他们输入0,然后将偶数和奇数相加。这是:

#include <stdio.h>;

int main() {
    int esum = 0, osum = 0;
    int n, mod;

    puts("Please enter some numbers, 0 to terminate:");
    scanf("%d", &n);

    while (n != 0) {
        mod = n % 2;
        switch(mod) {
        case 0:
            esum += n;
            break;
        case 1:
            osum += n;
        }
        scanf("%d", &n);
    }
    printf("The sum of evens:%d,\t The sum of odds:%d", esum, osum);
    return 0;
}

我通过命令提示符运行程序;它是使用Visual Studio为win32平台编译的。

之所以发生这种情况,是因为
scanf
函数从标准输入流获取其输入。它被称为流是有原因的:您输入的所有内容都被放入该流中,
scanf
读取该流。您在输入流中输入的任何内容都将保留在那里,直到像
scanf
这样的东西将其取出


换句话说,
scanf
并没有真正“记住”任何东西。正是输入流完成了所有的“记忆”。

请注意,每次通过循环时,您都在调用scanf();每次使用参数“%d”和&n调用scanf(),它都会将一个整数读入变量n,并前进到输入流中该整数之后的位置


您可以将输入流视为排序的“字符串”。假设我输入了“251600”;scanf()读取第一个整数后,输入流变为“16 0”;如果再次调用scanf(),将读取整数16,输入字符串将变为“0”。

C课程确实需要停止使用向人们介绍不良做法,例如使用
scanf
。作为旁注,您不需要在
#include
指令中附加分号。这是因为预处理的include文件中的分号结束了语句吗?或者因为编译器天生就通过其他方式“知道得更好”?在scanf()调用中/之后是否可能直接告诉它“只获取找到的第一个int”/显式清除剩余字符串的输入流?现在调用scanf()的方式确实是告诉它“只获取找到的第一个int”。例如,如果要使用scanf(“%d%d”、&a和&b),则scanf()会将找到的前两个整数读入a和b。至于你问题的第二部分,我不确定是否有“清除整个流”的标准方法,但你可以通过将“%d”更改为“%d%*s”使scanf忽略所有内容,直到行结束。你应该测试一下,看看会发生什么!如果您想了解更多有关scanf()的详细信息,特别是如何使用第一个参数,我建议您阅读手册页:诚然,这并不容易阅读,但如果您能够理解,您将真正了解如何使用scanf();fflush(stdin);scanf(“%d”和“b”);每次使用fflush(stdin)时都是这样;输入缓冲区被刷新(清除)。
-> Please enter some numbers, 0 to terminate:  
42 8 77 23 11 (enter)  
0 (enter)  
-> The sum of evens:50,     The sum of odds:111