繁体   English   中英

从文件C ++读取错误

[英]error reading from file C++

我在尝试从C ++中的文本文件读取时遇到此异常。

Windows在myprogram.exe中触发了一个断点。

这可能是由于堆损坏所致,这表明myprogram.exe或其已加载的任何DLL中均存在错误。

这也可能是由于myprogram.exe具有焦点时用户按下F12所致。

输出窗口可能包含更多诊断信息。

文本文件包含我要保存在双精度数组中的数字,这是我的代码:

double* breakLine(char arr[])
{
    double* row_data = new double[FILE_ROW_PARAMS];
    int j= 0, m= 0,k= 0;
    char str[FILE_ROW_SIZE]; 
    while(arr[j] != '\0')//not end of line
    {
        if(arr[j] == ' ')//significant data
        {
            str[k] = '\0';
            row_data[m++] = atoi(str);
            k = 0;
        }
        else if(arr[j]!=' ')
        {
            str[k++] = arr[j];
            if(arr[j+1] == '\0')
            {
                str[k] = '\0';
                row_data[m] = atoi(str);
            }
        }
        j++;
    }
    return row_data;
}

double* readFile(char fileName[],int* num,double* params)
{
    int size= SIZE, number_of_lines= 0;
    double* points = new double[SIZE * FILE_ROW_PARAMS];
    char arr[128];
    ifstream infile;
    infile.open(fileName);
    if(!infile) 
    {
        cout<<"NO FILE!";
        return NULL;
    }
    else
    {
        for(int i=0; i < NUMPARAM; i++) //get first params
        {
            infile >> params[i];
            size--;
        }
        infile.getline(arr,128);
        while(!infile.eof())
        {
            infile.getline(arr,128);
            double* a = breakLine(arr);
            for(int i=0; i < FILE_ROW_PARAMS; i++)
            {
                *(points+number_of_lines*FILE_ROW_PARAMS+i) = *(a+i);
            }
            number_of_lines++;
            size--;
            if(size == 0)
            {
                size = SIZE;
                points = (double*)realloc(points, number_of_lines + SIZE * FILE_ROW_PARAMS);
            }
        }
        infile.close();
        *num  = number_of_lines;
        return points;
    }
}

我不确定您的文本文件的结构。 但是您没有利用C ++库。 这是一个代码示例,该代码示例从文本文件中逐行读取数字并将其推入double的向量中。 它也按原样计算行数。 我注意到您正在读取整数(正在使用atoi()转换输入),因此我的示例也是如此。 在此示例中,我忽略了您从文件中读取的初始参数。

#include <fstream>
#include <string>
#include <vector>
#include <sstream>

int main()
{
    std::ifstream infile("c:\\temp\\numbers.txt");
    std::vector<double> result;
    std::string line;
    int lines = 0;
    while (std::getline(infile, line))
    {
        ++lines;
        std::stringstream instream(line);
        std::copy(std::istream_iterator<int>(instream), std::istream_iterator<int>(), std::back_inserter(result));
    }

    return 0;
}

暂无
暂无

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

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