当我试图在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;
}
}发布于 2013-11-04 01:50:58
我对你的文本文件的结构不是很确定。但是您并没有利用C++库。下面是一个代码示例,它逐行读取文本文件中的数字,并将它们推入双精度向量。它也会像你一样计算行数。我注意到您读取的是整数(使用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;
}https://stackoverflow.com/questions/19752407
复制相似问题