2014-03-06 189 views
0

我正在研究一个需要我读取仅由数字组成的.txt文件的小脚本。我对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(); 
} 

它按预期工作。有什么我应该纠正的,或者我可以这样离开吗?

+0

你能否包含函数声明?它返回什么? – charlieparker

+0

函数声明是什么意思?当我运行代码时,我只收到一个'浮点异常'输出,即使代码编译。 –

+0

没关系,我在那里看到它。我把它向下卷动太多了。这是您发布代码的第一行。 – charlieparker

回答

0

你不能使用.eof()多数民众赞成在很糟糕,并从C#说我会说试试while(sampleFile.good()) 并从那里去。

+1

'while(sampleFile.good())'比使用'.eof()'好不了多少,问题是标记是在读取失败后设置的,http://stackoverflow.com/questions/5605125/为什么 - 是 - iostreameof-内,一个循环条件考虑的,是错误的。 – Cramer