【问题标题】:Off by one error in while loop with eof()使用 eof() 在 while 循环中关闭一个错误
【发布时间】:2014-09-13 11:52:46
【问题描述】:

我在以下一段 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 . . .

【问题讨论】:

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


    【解决方案1】:

    解决此问题的最简单方法是不要在 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;
    

    【讨论】:

    • 现在我很好地意识到了这个问题......我将在我的代码中实现重新排序。谢谢。
    【解决方案2】:

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

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

    【讨论】:

    • 我将在 while 循环之后将 i 递减一次。这将解决问题。但是我不太清楚 eof() 是如何工作的,我应该研究一下。
    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多