【问题标题】:I/O with while and for loops [closed]带有 while 和 for 循环的 I/O [关闭]
【发布时间】:2017-04-11 09:15:05
【问题描述】:

编辑: 我现在明白我的怀疑是什么了。我不明白为什么在 while 循环开始时没有读取第一个值(N,值的数量),这是因为我当时不知道的一个非常简单的原因。 之所以发生,是因为之前在以下行读过它:

 ifile >> n;

我认为在while循环中文件读取将从头开始,而不是从最后读取的行开始。

对不起,如果我之前没有说清楚。我希望我现在。


我有一个文件,它代表实验中的测量值列表,如下所示:

N 
x_1  y_1 ex_1 ey_1
x_2  y_2 ex_2 ey_2
...  ... ...  ...

其中 N 是值的数量,x_1, x_2, ... 是值本身。 我必须将这些值放在一些数组中,所以我尝试了这个 while 循环:

int n;
double d,e,f,g;
while (ifile >> d >> e >> f >> g){
x[n]=d;
y[n]=e;
ex[n]=f;
ey[n]=g; 
n++;
}

但是当我编译时,我看到第一个值(N,即值的数量)被放入了第一个数组中,所以因为我必须对测量值进行计算,所以我不能使用它。 我发现通过使用这个 for 循环:

int n;
ifile >> n;
for(int i=0; i<n; i++) {
ifile >> x[i];
ifile >> y[i];
ifile >> ex[i];
ifile >> ey[i];
}

并打印出数组,“N”不被读取,读取从第一个值开始。为什么? (x,y,ex,ey 是动态数组)

这是完整的代码:

#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int main() {

  int n;

  ifstream ifile("pendulum.dat");
  if(!ifile){
    cout << "Error in file opening" << endl;
    return 1;
  }

  ifile >> n;
  double* x = new double[n];
  double* y = new double[n];
  double* ex= new double[n];
  double* ey= new double[n];
  double* py= new double[n];
  double* pey=new double[n];
  for(int i=0; i<n; i++) {
    ifile >> x[i];
    ifile >> y[i];
    ifile >> ex[i];
    ifile >> ey[i];
    py[i]=pow(y[i],2);
    pey[i]=2*(ey[i]/y[i])*pow(y[i],2);
  }

   double S0=0,Sx=0,Sy=0,Sxx=0,Sxy=0;

   for(int i=0;i<n;i++){
    S0 = S0 + 1/pow(pey[i],2);
    Sx = Sx + (x[i]/pow(pey[i],2));
    Sy = Sy + py[i]/pow(pey[i],2);
    Sxx = Sxx + pow(x[i],2)/pow(pey[i],2);
    Sxy = Sxy + (x[i]*py[i])/pow(pey[i],2);
  }

 double a,b,ea,eb;
 a=((Sxy*S0)-(Sx*Sy))/((Sxx*S0)-(Sx*Sx));
 ea=sqrt((S0)/((Sxx*S0)-(Sx*Sx))); 
 b=((Sy*Sxx)-(Sx*Sxy))/((Sxx*S0)-(Sx*Sx)); 
 eb=sqrt((Sxx)/((Sxx*S0)-(Sx*Sx))); 

 cout <<"Value of a is "<< a<<" +- "<<ea<< endl;
 cout <<"Value of b is "<< b<<" +- "<<eb<< endl;


  double g,eg;
  double k=4*pow(M_PI,2);
  g=k/a;
  eg=k*ea;
  cout<<"Value of g is "<<g<<" +- "<<eg<< endl;


  ifile.close();
  return 0;  
  } 

【问题讨论】:

  • 我认为应该在for循环之前添加这一行。 ifile &gt;&gt; n
  • 我忘了在问题中复制那个(和int n;),但它们在代码中
  • 您的代码有效吗?如果没有,请尝试使用ios::binary打开文件!
  • 它一直有效;我不明白为什么。现在我知道了。

标签: c++ for-loop file-io while-loop


【解决方案1】:

你想要的

int n;
ifile >> n;
for(int i=0; i<n; i++) {
    ifile >> x[i];
    ifile >> y[i];
    ifile >> ex[i];
    ifile >> ey[i];
}

也许?

【讨论】:

  • 我猜你是对的!
  • @kiner_shah 是的,这里纯属猜测;)
  • 我忘了复制问题中的这两行。
  • @πάνταῥεῖ 我编辑了这个问题,看看现在是否正确;)
  • @kiner_shah 我终于明白了这个问题。很明显,你可能认为我知道是理所当然的
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
相关资源
最近更新 更多