【发布时间】:2015-11-20 18:30:08
【问题描述】:
我正在编写一个小脚本,该脚本需要我读取一个仅由数字组成的 .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();
}
它按预期工作。有什么我应该更正的吗,还是我可以这样吗?
【问题讨论】:
-
可以包含函数声明吗?它返回什么?
-
函数声明是什么意思?当我运行代码时,即使代码编译,我也只会收到“浮点异常”输出。
-
没关系,我在那里看到了。我把它向下滚动得太远了。这是您发布的代码的第一行。
-
“我没有得到错误”和“我得到输出浮点异常”怎么可能都是真的?您能分享有关异常的任何详细信息吗?
-
我在 linux 中用 g++ 编译它。当我编译它时,不会出现错误。
floating point exception是我在控制台中运行它时得到的输出。之前的所有代码都可以正常工作,在我的例子中,这只是一条 cout 消息“Hello”,以检查它在此之前是否工作。 @ScottHunter
标签: c++ text-files