I am trying to read in several lines, each should have exactly 5 pieces of data. I am using try/catch/throw to determine if the data is in the correct format, and trying to use iss to separate the parts. However, this is my first time using both, and I am pretty certain that I am missing something obvious. Firstly, by debugging, I found that the first piece of data is being checked in the second case, giving me errors. I believe I may need to read in more from the iss>> than just the one, but I am lost. Any suggestions?? Here is my code:
Code:
ifstream indata;
ifstream indata2;
string instring;
string instring2;
istringstream iss_string;
istringstream iss_string2;
string data[5];
string data2[5];
int count = 0;
int count2 = 0;
int datacount = 0;
int offset;
int offset2;
indata.open("student.data");
if(!indata){
cout<<"student.data file could not be opened.";
exit(1);}
while(indata){
getline(indata, instring);
try{
while(instring != "0"){
iss_string.str(instring);
iss_string >> data[count];
datacount++;
offset = iss_string.tellg();
while(offset >= 0){
switch(count){
case 0:
if(data[count].length() != 9){
throw 0;
break;
}
for(int i=0; i < (data[count].length()); i++){
if(!isdigit(data[count][i])){
throw 0;
break;
}
}
case 1:
if(data[count].length() > 30 || data[count].length() < 1){
throw string("Invalid number of characters in Last Name of student.data file");
break;
}
for(int i=0; i<data[count].length(); i++){
if(!isalpha(data[count][i])){
throw string("Invalid characters in Last Name of student.data file");
break;
}
}
case 2:
if(data[count].length() > 30 || data[count].length() < 1){
throw string("Invalid number of characters in First Name of student.data file");
break;
}
for(int i=0; i<data[count].length(); i++){
if(!isalpha(data[count][i])){
throw string("Invalid characters in First Name of student.data file");
}
}
case 3:
if(data[count].length() != 2){
throw string("Invalid number of characters in Major of student.data file");
break;
}
for(int i=0; i<data[count].length(); i++){
if(!isalpha(data[count][i])){
throw string("Invalid characters in Major of student.data file");
}
}
case 4:
if(data[count].length() != 2){
throw string("Invalid number of characters in Year of student.data file");
}
for(int i=0; i<data[count].length(); i++){
if(!isalpha(data[count][i])){
throw string("Invalid characters in Year of student.data file");
}
}
//break;
}
}
}
count++;
iss_string>>data[count];
offset = iss_string.tellg();
if(datacount != 5){
throw string("Invalid number of items in line of student.data.");
//break;
}
getline(indata, instring);
iss_string.clear();
count = 0;
}
catch(int x){
cout<<"Invalid ID number in student.data file";
exit(1);
}
catch(string s){
cout<< s <<endl;
exit(1);
}
}
indata.close();
Comment