Question
Were supposed to read only valid data into our program by the format( F=firstname,L=lastname,V=votes) for example from this F=John,L=Smith,V=3342 F=Stan,L=SmithV=4429 F=Thomas,X=Anderson, V=1622 F=Catherine,L=Johnson,V=2004 so John
Were supposed to read only valid data into our program by the format( F=firstname,L=lastname,V=votes) for example from this
F=John,L=Smith,V=3342 F=Stan,L=SmithV=4429 F=Thomas,X=Anderson, V=1622 F=Catherine,L=Johnson,V=2004
so John Smith and Catherine Johnson should be read but invalid input ignored, how can i do this, our only hint was to use substr() and find() since we read the whole line as a string? ( my code below skips incorrect string lines and the next line, instead of just the incorrect line)
Correct input should be (ie John Smith 3342)
void readFile(Candidate candidates[], int& n ) { string line; ifstream infile; int pos1, pos2, pos3; n= 0; infile.open("elections.txt"); while(!infile.eof() ) { getline(infile,line) ; pos1=line.find("F="); if (pos1 == string::npos) infile.ignore(100, ' ' ) ; else { line= line.substr(pos1 +2,line.length()-2); pos2 = line.find(",L="); if (pos2 ==string:: npos) infile.ignore(100, ' ' ) ; else {
candidates[n].first= line.substr(0,pos2); line= line.substr(pos2+3,line.length()-3); pos3= line.find(",V="); if (pos3 ==string:: npos)
infile.ignore(100, ' ' ); else{ candidates[n].last= line.substr(0,pos3); line= line.substr(pos3+3,line.length()-3); stringstream ss; ss< ss>>candidates[n].votes; //convert string into int and store it in "asInt" ss.str(""); //clear the stringstream ss.clear(); // candidates[n].pScore= 0; } }} n++; } infile.close();}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started