[转载]读书笔记——《C Primer Plus》: 利用scanf()函数的返回值


先列出一段代码:
Listing 6.1. The summing.c Program
/* summing.c -- sums integers entered interactively */

#include <stdio.h>

int main(void)

{

    long num;

    long sum = 0L; /* initialize sum to zero */

    int status;



    printf("Please enter an integer to be summed ");

    printf("(q to quit): ");

    status = scanf("%ld", &num);

    while (status == 1) /* == means "is equal to" */

    {

        sum = sum + num;

        printf("Please enter next integer (q to quit): ");

        status = scanf("%ld", &num);

    }

    printf("Those integers sum to %ld.\n", sum);



    return 0;

}

scanf()函数返回成功赋值的变量的个数,或者返回EOF,如果出错。
在这段程序中,scanf("%ld", &num);语句是想通过用户输入给变量num赋值,如果输入的是长整型变量,
则返回1,否则如果输入任何非整型变量,返回0。利用这个特性,可以很方便的告诉我们,用户输入是否是
合法数据。
在Programming Exercise 5.8中,也可以利用scanf()的这个特性来决定循环是否继续进行。代码如下:
 
/* Programming Exercise 5-8 */
#include <stdio.h>
void temperatures(double fahr);
int main() {
    double fahr;
    printf("Please enter the tempurature in Fahrenheit (q to quit): ");

    while (scanf("%lf", &fahr) == 1) {
        temperatures(fahr);
        printf("Please enter another temperature in Fahrenheit (q to quit): ");
    }
    return 0;
}
void temperatures(double fahr) {
    const double fahr_to_celsius = 32.0;
    const double celsius_to_kelvin = 273.16;
    double celsius, kelvin;
    celsius = 1.8 * fahr + fahr_to_celsius;
    kelvin = celsius + celsius_to_kelvin;
    printf("The temperature in Fahrenheit is %.2f.\n", fahr);
    printf("The temperature in Celsius is %.2f.\n", celsius);
    printf("The temperature in Kelvin is %.2f.\n", kelvin);
}

你可能感兴趣的:(scanf()返回值)