简体   繁体   English

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

[英]Why is my program printing the last input line twice?

My program is supposed to print what my input give reading it letter by letter with a scanf and saving them in variables when after they print whats inside them.我的程序应该打印我输入的内容,用 scanf 一个字母一个字母地阅读它,并在他们打印里面的内容后将它们保存在变量中。 This in a cycle so it can print every line.这是一个循环,所以它可以打印每一行。 But it seems it either is scanning the last line two times or printing it two times但它似乎要么扫描最后一行两次要么打印两次

I tried putting \\n inside the scans which solve the printing problem but now it wouldn't print the first letters of each line我尝试将 \\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;
}

This is my input and my expected output:这是我的输入和我的预期输出:

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

This is my actual output:这是我的实际输出:

 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
  • scanf is reading values into variables that aren't cleared before each run. scanf正在将值读入每次运行前未清除的变量中。
  • You aren't checking the return value of scanf to make sure that it succeeded.您没有检查scanf的返回值以确保它成功。
  • scanf doesn't read the newline at the end of the input, but the scanf('%c') does. scanf不会读取输入末尾的换行符,但scanf('%c')会读取。

Together this means after you read your last line of input, you loop back, while(scanf(…)) successfully reads in the final newline, your other scanf fails because there's no more input, and the printf prints the stale data inside the local variables.这意味着在您读取最后一行输入后,您循环返回, while(scanf(…))成功读取了最后的换行符,您的另一个scanf失败,因为没有更多输入,并且printf在本地打印陈旧数据变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM