1

My C++ program compiles and works up until I call this function from main():

int uword(){fstream infile("numbers.txt");
fstream exfile("wordlist.txt");
string numb[numoflines];
string lines[numoflines];  
number = 1; 
line = 1;  
for(int i=0;i<numofline;++i)
    {
    getline (infile,number);
    numb[i] = number; //I think this is causing the problem
    getline (exfile,line);
    lines[i] = line; //This too
    }
infile.close();
exfile.close();    
string yourword;

Something here causes it to crash, in the debug it pops up with "An access violation (Segmentation Fault) raised in your program."

EDIT: My mistake was using !infile.eof in the for loop.

Mark
  • 73
  • 7
  • Your input loop is incorrect. GMan gave a good explanation of how to properly handle input in [an answer to one of the C++ FAQ questions](http://stackoverflow.com/questions/4258887/semantics-of-flags-on-basic-ios/4259111#4259111). – James McNellis Jan 01 '11 at 18:48
  • Changing !infile.eof() to i<=numoflines (Which should do the same thing) still gives me the error. I think that is what you meant by your reference. – Mark Jan 01 '11 at 19:08
  • Do you mean i – AJ. Jan 01 '11 at 19:33
  • Yes that is what I meant, and when I changed it in my code it works now. :) – Mark Jan 01 '11 at 19:41

2 Answers2

3

Not a direct answer, but I believe it's a good one...

Use The Debugger! GDB should suspend at the exact line when the segmentation fault happens, thus giving you a very good hint about what the error is.

Kos
  • 70,399
  • 25
  • 169
  • 233
1

The getline function does not work the way you think it works.

Also, there could be more than numoflines lines in infile.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • Could you elaborate on the proper use of 'getline'? numoflines was calculated previously by how many lines were in the file. – Mark Jan 01 '11 at 18:59
  • @Mark : See `man 3 getline`. It's designed for use with C `FILE*` handles, and you're trying to use it here with an `fstream`. You should do `infile >> number` to use a C++-style `ifstream`. – Borealid Jan 01 '11 at 19:11
  • I am using getline becuase it seems to work for this purpose. infile >> number would just write the whole file to number right? – Mark Jan 01 '11 at 19:25