【问题标题】:Why does command prompt show numbers before I begin?为什么在我开始之前命令提示符会显示数字?
【发布时间】:2015-08-23 21:20:51
【问题描述】:

命令提示符在程序开始前显示数字。为什么? 2687688 已给出 但数字不会写入文件?

#include <stdio.h>
#include <conio.h>

int main(void){
    FILE*nfPtr;
    int n;
    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL)
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 1 begin

    printf("Enter numbers to be stored in file\n");
    printf("%d",&n);
    while (!feof(stdin)){
          fprintf(nfPtr,"%d",n);
          scanf("%d",&n);
          }
}//else 1 ends
        fclose(nfPtr);

getch();
return 0;
}

【问题讨论】:

  • 因为你有printf("%d",&amp;n); - 你的编译器不会发出警告吗?
  • 另外,将fclose(nfPtr) 移动到else 块的主体中​​。因为fclose(NULL) 是UB。

标签: c file-io printf scanf


【解决方案1】:

除了其他问题,在您的代码中

 printf("%d",&n);

绝对错误并调用undefined behaviour。 .也许你的意思是

 scanf("%d",&n);

扫描号码。

也就是说,请看,why you should refrain from using !feof(file)

【讨论】:

    【解决方案2】:

    替换

    printf("%d",&n);
    

    scanf("%d",&n);
    

    printf将format指向的C字符串写入标准输出(stdout)

    scanf从标准输入读取数据

    在您的代码中,您正在打印未初始化的 n,即在 "Enter numbers to be stored in file" 字符串之后打印出一个随机数。

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2020-02-26
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多