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.
Input
The 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.
Output
Output 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 clipboard
abcdefabcdefabcdefab
1234567 abcdefabcdefabcdefab
9876543 abddefbbbdefcbcdefac
5554446 abcdefabcdefabcdef
4445556 abcdefabcdefabcdefabcd
3332221 abcdefghijklmnopqrst
0
Sample Output
1234567 20
9876543 15
5554446 Too few answers
4445556 Too many answers
3332221 Invalid answers
PHP中文网2017-04-17 14:54:10
#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;
}
else
return -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(" %d\n", rignum);
scanf("%d", &sid);
}
}
}
VC++2010 測試沒問題。