用C++读取.txt文件
Reading a .txt file with C++
我正在编写一个小脚本,该脚本要求我读取一个仅由数字组成的.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())然后从那里出发。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 我可以读取静态对象中的文件.txt吗?C++
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 具有文件.txt的 C++ 中的设置
- 如何在 CMakeList 中包含 h/hpp 头文件.txt而不是 cpp 或其他 hpp 文件
- 使用函数读取文件.txt中的矩阵
- 任何人都知道如何解决尝试将从MySQL数据库返回的行打印到文本文件(.txt)中的C++
- 读取文件.txt C
- 为什么我的方法不从文件.txt中读取float类型
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- 读取文件".txt"并将每行的数据分配给循环列表中的新节点C++
- 如何用C++将字符串文件Txt解析成数组
- 如何在c++中读取和编辑文件txt
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 导入文件txt时出错
- 如何仅读取文件.txt中的数字