繁体   English   中英

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

[英]Off by one error in while loop with eof()

我在下面的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 . . .

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

尝试正确循环eof()good()存在一些众所周知的问题,请阅读以下问题的示例: 为什么在循环条件内的iostream :: eof被认为是错误的? 测试stream.good()或!stream.eof()读取最后一行两次

您可以对代码重新排序,以便仅在成功读取值后才将i递增:

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

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

循环结束后,您将希望减小i一次。 请记住,此处计算的是发现的样本数量(比循环运行的次数少一个)与尝试填充的数组中的元素数量之间的区别。

暂无
暂无

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

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