用C++读取.txt文件

Reading a .txt file with C++

本文关键字:文件 txt 读取 C++      更新时间:2023-10-16

我正在编写一个小脚本,该脚本要求我读取一个仅由数字组成的.txt文件。我对C++不太熟悉,所以我的教授给了我们以下函数,它应该允许我们读取.txt文件:

(很抱歉把整个函数放在这里,但由于我缺乏知识,我不能写一个最小的例子。)

int * ReadDataSample(const char * filename,int * NoSamples, int * NoApcs){
ifstream SamplesFile;
int Counter = 0;
float data = 0;
int  * p = NULL;
char * s = NULL;
SamplesFile.open(filename,ios::in);
if(SamplesFile.is_open())
{
while(!SamplesFile.eof())
{
SamplesFile >> data;
Counter++;
}
SamplesFile.clear();
SamplesFile.seekg (0, ios::beg);
// read line
s = new (nothrow) char[Counter];
if(s == 0) { cout <<"Error: opening file for reading - could not allocate memory..." << endl; exit(EXIT_FAILURE); }
(*NoSamples) = 0;
// count number of samples in s 
while (SamplesFile.getline(s, Counter))
{
++(*NoSamples);
}
(*NoApcs) = Counter/(*NoSamples);
SamplesFile.clear();
SamplesFile.seekg (0, ios::beg);
delete [] s;
}else{ cout << " Error opening file... exiting"<< endl; exit(EXIT_FAILURE);}

// allocate memory...
if(Counter != 0)
{   
p = new (nothrow) int [Counter];
if(p == 0) { cout <<"Error: opening file for reading - could not allocate memory..." << endl; exit(EXIT_FAILURE); }
for(int i = 0; i < Counter && SamplesFile.eof()!=true; i++)
{
SamplesFile >> data;
p[i] = (int)data;
}
return p;
}else{
return NULL;
}
}

我试图通过首先启动指向int:的指针来调用此函数

int NoLines = 480, NoColumns = 640;
int * p;
p = ReadDataSample("file.txt",& NoLines, & NoColumns);

然而,当我运行代码时,我没有得到错误,但我得到了输出浮点异常在控制台中。现在,我的主页上只有一个带信息的cout。

如果有人能为我指明正确的方向,我将不胜感激。

编辑:

由于每个人似乎都同意现在给我的代码不是最好的选择,我决定使用从网上收集的信息创建一个新的代码。我有这个:

void grabI(Qstruct & q){
cout << "in grabI" << endl;
int counter = 0;
int i = 0;

ifstream myfile;
myfile.open("data.txt",ios::in);
if(myfile.is_open()){
while(!myfile.eof()){
myfile >> i;
counter++;
}
counter--;
myfile.close();
myfile.open("data.txt",ios::in);    
for(i=0;i<counter;i++){
myfile >> q.I[i];   
}

}
else{
cout << "Unable to read file." << endl;
}   
myfile.close(); 
}

它按预期工作。里面有什么我应该纠正的吗?或者我可以就这样算了吗?

你不能使用.of(),这很糟糕,通常来自C#,我会说try-while(sampleFile.good())然后从那里出发。