c - 跳过输入文件行的程序

标签 c input output

我有一个程序,它应该询问你温度,然后在 Planck 函数中使用该温度。波长位于名为“inputwave.dat”的文件中 看起来像

500
1000
1500
2000
.
.
.
11500
12000

(500 到 12,000 之间的间隔。每行各占一行)

我遇到的问题是它只打印每隔一行。

原来如此

"500 ....
1500 ....
2500 ....
3500 ...."

我希望它打印出每一行,在我的代码中发生这种情况的地方我似乎找不到任何会导致它跳过一行的内容。

#include <stdio.h>
#include <stdlib.h> 
#include <math.h>
double planck(double wave, double T);
int main()
{
  double wave,T;
  double result;
  int ni;
  char outfile[80];
  FILE *out,*in;
  in = fopen("inputwave.dat","r");
  printf("\nEnter the temperature in Kelvin > ");
  ni = scanf("%lf",&T);
  printf("\nEnter the name of the output file > ");
  ni = scanf("%s",outfile);
  if((out = fopen(outfile,"w")) == NULL)
  {
    printf("\nCannot open %s for writing\n",outfile);
    exit(1);
  }
  while(fscanf(in,"%lf",&wave) != EOF)
  {
    fscanf(in,"%d",&wave);
    result = planck(wave,T);
    fprintf(out,"%7.1f %e\n",wave,result);
  }
  fclose(out);
  return(0);
}
double planck(double wave, double T)
{
  static double p = 1.19106e+27;
  double p1;
  p1 = p/(pow(wave,5.0)*(exp(1.43879e+08/(wave*T)) - 1.0));
  return(p1);
}

感谢您的宝贵时间。

最佳答案

首先,试试这个(即不要调用 fscanf 两次):

while(fscanf(in,"%lf",&wave) != EOF)
{
  result = planck(wave,T);
  fprintf(out,"%7.1f %e\n",wave,result);
}

之后让我们正确检查fscanf 的返回值。此函数返回成功填充的参数列表的项目数。所以,这个while的主体只有在这个返回值恰好为1时才应该被执行。所以,最好更改检查:

while(fscanf(in,"%lf",&wave) == 1)

关于c - 跳过输入文件行的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564299/

相关文章:

c - 如何检查我的数组是否按升序排列?

c - ZeroMQ 的网络诊断示例

C 读取套接字偶尔发生变化

angularjs - 更改范围变量中的值后, Angular 表单验证无效

c - 为什么将标准输出重定向到文件时,C 程序的输出顺序不同?

C编程: array not have any bound

html - 为什么我的 "oninvalid"属性让模式失败?

java - 是否可以获取一个字符串并将其放入 System.in 中?

java - 如何在 Java 中使用 printf 格式化多行 toString()

excel - 为什么Range.BorderAround向控制台发出 “True”?