为什么我的程序将最后一个输入行打印两次?

时间:2019-09-11 02:48:51

标签: c printf scanf

我的程序应该打印输入内容,以便阅读 带有scanf的字母,并在打印后将其保存在变量中 什么是 在他们里面。这样可以循环打印每行。但似乎 要么扫描最后一行两次,要么将其打印两次

我尝试将\ n放入扫描中以解决打印问题,但是 现在不会打印每行的首字母

    #include <math.h>
    #include <stdio.h>

    int main()
    {
    double tempG = 0;
    double altG = 0;
    double humG = 0;

    char cultivo[100] = " ";

    char  nombre[100] = " ";
    double temp = 0;
    double alt = 0;
    double hum = 0;

    char insertado;

    int contador = 0;
    scanf("%lf %lf %lf" , &tempG, &altG, & humG);
    printf("%2.0lf %2.0lf %2.0lf \n \n", tempG, altG, humG);
    char temporal[100] = "";
    while(scanf("%c", &insertado) != EOF){
            scanf("%s %lf %lf %lf", nombre, &temp, &alt, &hum);
            printf("%s %.0lf %.0lf %.0lf \n", nombre, temp, alt, hum);

        }


    return 0;
    }

这是我的输入和预期的输出:

25 65 1200

Banano 27 50 1000
Brocoli 16 75 2500
Fresas 18 80 2000
Zanahoria 21 75 1200
Tomate 22 75 1000

这是我的实际输出:

25 65 1200

Banano 27 50 1000
Brocoli 16 75 2500
Fresas 18 80 2000
Zanahoria 21 75 1200
Tomate 22 75 1000
Tomate 22 75 1000

1 个答案:

答案 0 :(得分:1)

  • scanf正在将值读入每次运行之前未清除的变量。
  • 您不是要检查scanf的返回值来确保它成功。
  • scanf不会在输入末尾读取换行符,但是scanf('%c')会读取。

这意味着,在您读完最后一行输入后,您将循环返回,while(scanf(…))成功读入最后一个换行符,而其他scanf则因为没有更多输入而失败,并且{{1 }}在本地变量中打印陈旧的数据。