问题描述
write a program to grade a multiple-choice exam. The exam has 20 questions, each answered with a letter in the range of ‘a’ through ‘f’.The program should read the key from input, then read each answer and output the ID number and score. Erroneous input should result in a error message.InputThe first line of input is the key, consisting of a string of 20 characters. The remaining lines are exam answers, each of which consists of a student ID number, a space, and a string of characters.The input ends with 0. OutputOutput the score for each ID number in a sigle line, consisting the ID number, a space, and the score or error message. Sample Input Copy sample input to clipboardabcdefabcdefabcdefab1234567 abcdefabcdefabcdefab9876543 abddefbbbdefcbcdefac5554446 abcdefabcdefabcdef 4445556 abcdefabcdefabcdefabcd3332221 abcdefghijklmnopqrst0Sample Output1234567 209876543 155554446 Too few answers4445556 Too many answers3332221 Invalid answers
问题解答
回答1:#include <iostream>#include <vector>#include <string>using namespace std;bool isAnswerValid(string ans){ if(ans.length()<20) {cout << ' Too few answers' << endl;return false; } else if(ans.length() > 20) {cout << ' Too many answers' << endl;return false; } for(auto i=ans.begin(); i!=ans.end(); i++)if( (char)*i<’a’ || (char)*i>’f’) { cout << ' Invalid answers' << endl; return false;} return true;}int howManyRightAnswer(string ans, string stu){ int val = 0; if(isAnswerValid(stu)==true) {auto i = ans.begin();auto j = stu.begin();while(i!=ans.end()) { if( *i == *j)val++; i++; j++;}return val; } elsereturn -1; }int main(void) { string ans, stu; int sid, rignum; cin >> ans; if (isAnswerValid(ans)==true) {scanf('%d', &sid);while(sid!=0) { cin >> stu; cout << sid; rignum = howManyRightAnswer(ans,stu); if(rignum!=-1)printf(' %dn', rignum); scanf('%d', &sid);} }}
VC++2010 测试没问题。