segmentation fault

hi guys, i am new to c++ and unix.

I have my code written and it can be compile successfully. Not sure where the problem is (I checked the pointer part, it should be fine). I highlighted the part in bold which I think might cause the problem. Thanks a lot !


#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdio.h>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <sstream>

using namespace std;

int main(){
ifstream fin;
ofstream fout;
string filename;
string temp;

cout << "Enter input file: ";
cin >> filename;

fin.open(filename.c_str());
if(!fin){
cerr << "Input file can not be opened!" << endl;
exit (-1);
}

fout.open ("output_file.txt");

fout << "Name Score1 Score2 Score3 Score4 Total Grade"<< endl;


int lineCount = 0; // lineCount will be the number of lines read from input file;

while (!fin.eof()){
getline(fin,temp);
++lineCount; // count how many lines in the input file;


string buf;
stringstream ss(temp);
vector<string> tokens;

while (ss >> buf)
tokens.push_back(buf); // Not sure about this part;



double score[4]; // Create a double array to contain all the 4 scores in each line;
double total=0; // to calculate the total of 4 scores for each student;
string grade;
int Total;


for (int i=0; i<4; i++){

score[i] = atof (tokens[i+1].c_str()); // convert each score in string type into double type and copy into the array

total += score[i]; // calculate the total of 4 scores;

}

Total = int (total); // convert the total in double type into integer;

if(Total>=95 && Total<=100){
grade = "A";
}
else if(Total>=90 && Total<95){
grade = "A-";
}
else if(Total>=85 && Total<90){
grade = "B+";
}
else if(Total>=80 && Total<85){
grade = "B";
}
else if(Total>=75 && Total<80){
grade = "B-";
}
else if(Total>=70 && Total<75){
grade = "C+";
}
else if(Total>=65 && Total<70){
grade = "C";
}
else if(Total>=60 && Total<65){
grade = "C-";
}
else if(Total>=50 && Total<60){
grade = "D";
}
else if(Total>=0 && Total<50){
grade = "F";
}





fout << tokens[0] << "\t" << score[0] << "\t" << score[1] << "\t" << score[2] << "\t" << score[3] << "\t" << total << "\t" << grade << endl;

}
fin.close();
fout.close();
return 0;
}


I'd really appreciate it if you used [code] blocks so that I could give you line numbers.

Your segmentation fault probably doesn't occur in any of the bolded lines, but most likely in the loop just after it. Do you see the problem you have with the index when you're using the vector's []?

-Albatross

P.S.: Not to be rude or anything, but maybe you should read these for future posts:
http://cplusplus.com/forum/beginner/1/#msg6680
http://cplusplus.com/articles/firedraco1/
Last edited on
score[i] = atof (tokens[i+1].c_str()); // convert each score in string type into double type and copy into the array will crash (segmentation fault) when tokens.size() < 5
Topic archived. No new replies allowed.