使用eof()在while循环中关闭一个错误

时间:2014-07-22 15:11:28

标签: c++ do-while eof off-by-one

我在下面的C ++代码中有一个错误的错误,我无法弄明白。任何人都可以帮忙。我有下面的代码及其输出。最好的。

double* alloc_Array=new double[m_int_NumChann*m_int_NumSamples];
int int_SizeArray=int(0);
std::ifstream File;
File.open(m_char_Address);
if(File.is_open()){
    std::cout<<"input file opened...\n";
    int i=int(0);
    do{
        File>>alloc_Array[i];
        i++;
    }while(!File.eof());
    int_SizeArray=i;
}else{
    std::cerr<<"ERROR: input file can't be opened.\n";
    system("pause");
}
File.close();
if((m_int_NumChann*m_int_NumSamples)!=int_SizeArray){
    std::cerr<<"WARNING: number of samples multiplied by number of channels is not equal to total data points in the input file:\n";
    std::cerr<<"       number of samples in each channel = "<<m_int_NumSamples<<'\n';
    std::cerr<<"       number of channels = "<<m_int_NumChann<<'\n';
    std::cerr<<"       total data points by multiplication = "<<m_int_NumSamples*m_int_NumChann<<'\n';
    std::cerr<<"       number of data points in the input file = "<<int_SizeArray<<'\n';
    system("pause");
}

输出:

   input file opened...

   WARNING: number of samples multiplied by number of channels is not equal to tota
   l data points in the input file:

   number of samples in each channel = 77824

   number of channels = 11

   total data points by multiplication = 856064

   number of data points in the input file = 856065

   Press any key to continue . . .

2 个答案:

答案 0 :(得分:3)

解决此问题的最简单方法是不在eof()循环。

尝试正确循环eof()good()时存在众所周知的问题,请阅读以下问题以获取示例:Why is iostream::eof inside a loop condition considered wrong?Testing stream.good() or !stream.eof() reads last line twice

您可以对代码重新排序,以便只有在成功读取值后才会增加i

int i=int(0);
while (File >> alloc_Array[i]) {
    i++;
}
int_SizeArray=i;

答案 1 :(得分:2)

在do {} while()循环中,每次都递增i。考虑零长度文件的情况。循环的第一次传递将发生,之后我将等于1.由于将立即到达EOF,因此不会发生后续传递。但是,在这种情况下实际上没有找到样品。

你想要在循环结束后减少一次。记住计算找到的样本数量(比循环运行的次数少一个)和尝试填充的数组中的元素数量之间的区别。