I was hoping someone could help me with a segmentation fault I'm getting, I'm posting more code this time in hopes everyone can see what I'm trying to do. I'm sure it has to do with how I point to everything as that's the part that I'm having trouble with. This is the .h
using namespace std;
// Data
struct question{
string programNum;
string programDesc;
string programPoints;
string programInput;
char* programQuestion;
};
void setQuestionFileName(question* q, char* fileName);
void display(question* q);
void display(question* q);
This is the .cpp
using namespace std;
void setQuestionFileName(question* q, char* fileName){
strcpy(q->programQuestion, fileName);
}
void display(question* q){
cout << "Description = " << q->programDesc << endl;
cout << "Number of Points = " << q->programPoints << endl;
cout << "Name of Question File = " << q->programQuestion << endl;
}
// Not used or tested yet
int myCompare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa,pb);
}
And main.cpp:
using namespace std;
int main(int argc, char* argv[]){ //or char** argv
question* questions[argc-1]; //Array of questions to be filled by loop.
int sizeOfQuestions = argc; //number of questions passed in at run time
int numLines = 0; //number of lines in file
for(int i=0;i<argc;i++){ //Test loop to make sure the command line file names are read in
std::cout << argv[i] << " says hello" << std::endl;
}
for(int count=0;count<sizeOfQuestions-1;count++){ //This loop places the information from the files into structs
//char fileName = argv[count+1];
char* fileName = argv[count+1];
cout << "Problem number: " << count+1 << "\t Working with file " << fileName << endl;
std::fstream questionFile (fileName, std::fstream::in); //Open the file
if(questionFile.good()){
cout << "File Opened" << endl;
setQuestionFileName(questions[count],fileName);
cout << questions[count]->programQuestion << endl;
getline(questionFile,questions[count]->programNum);
getline(questionFile,questions[count]->programDesc);
getline(questionFile,questions[count]->programPoints);
getline(questionFile,questions[count]->programInput);
display(questions[count]);
questionFile.close();
}else{
cout << "Could not open file!!!" << endl;
}
}
return 0;
}
And lastly, the output:
$ ./a.exe q1.txt q2.txt
./a says hello
q1.txt says hello
q2.txt says hello
Problem number: 1 Working with file q1.txt
File Opened
Segmentation fault (core dumped)