我想让程序读取一个包含20个单字符的文本文件,每个字符都在独立的一行。然后我想把这些字符与程序中预设的字母进行比较,从而输出不匹配的字符和总不匹配数。我已经成功地构建了手动输入字母的程序,它可以按照我的意愿执行,但是我对代码内部使用文件的知识有限。我已经阅读了关于向量的资料,但我想先保持简单,掌握基础知识,然后再尝试学习其他东西。我尝试设置了一些代码,看起来应该是正确的,但我无法弄清楚连接的最后几个步骤。请问有没有人能够指导我朝正确的方向前进呢?谢谢!借助这个论坛的帮助,我正在学到比我想象中更多的东西。
#include <iostream>
#include <conio.h>
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
void input(char[], int); //Function prototype
void checkAnswers(char[], char[], int, int);
int main()
{
const int NUM_QUESTIONS = 20;
const int MIN_CORRECT = 15;
int correctAnswers = 0; //Accumulator for number of correct answers
int incorrectAnswers = 0; //Accumulator for number of incorrect answers
char answers[NUM_QUESTIONS] = { 'B', 'D', 'A', 'A', 'C',
'A', 'B', 'A', 'C', 'D',
'B', 'C', 'D', 'A', 'D',
'C', 'C', 'B', 'D', 'A'};
char stu_answers[NUM_QUESTIONS];
ifstream infile;
infile.open("key.txt");
//Check for Error
if (infile.fail())
{
cerr << "Error Opening File" << endl;
exit(1);
}
string s1;
int count = 0;
// Reads file to the end
while (!infile.eof()) {
infile >> s1 >> stu_answers[NUM_QUESTIONS];
count++;
}
cout << count << " Students Answers" << endl;
checkAnswers(answers, stu_answers, NUM_QUESTIONS, MIN_CORRECT);
system ("pause");
return 0;
}
void checkAnswers(char answers1[], char stu_answers1[], int NUM_QUESTIONS, int
MIN_CORRECT)
{
cout << "max: " << NUM_QUESTIONS;
int correctAnswers = 0;
int incorrectAnswers = 0;
int wrongAnswers[]= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int j = 0;
//Check the student's replies against the correct answers
for (int i = 0; i < NUM_QUESTIONS; i++)
{
if (answers1[i] == stu_answers1[i])
correctAnswers++;
else if (answers1[i] != stu_answers1[i])
{
incorrectAnswers++;
wrongAnswers[j] = i + 1;
j++;
}
}
//Did they pass or fail?
if (correctAnswers >= MIN_CORRECT)
{
cout << "\nYou must have at least 15 correct to pass.";
cout << "\nStudent passed the exam\n\n";
}
else
{
cout << "\nYou must have at least 15 correct to pass.";
cout <<"\nStudent failed the exam\n\n";
}
//Display a list of the questions that were incorrectly answered.
cout << "The list below shows the question numbers of the incorrectly";
cout << " answered questions.\n";
for (int i = 0; i < NUM_QUESTIONS; i++)
{
if (wrongAnswers[i] != 0)
cout << "Question # " << wrongAnswers[i] << " is incorrect." << endl;
}
//Display the number of correct and incorrect answers provided by the student.
cout << "\nCorrect Answers = " << correctAnswers << endl;
cout << "Incorrect Answers = " << incorrectAnswers << endl;
}
这个文本文件只是一个名为“key”的记事本.txt文件,其中包含以下内容:
C
D
A
A
C
A
D
C
C
D
B
C
D
A
D
C
A
A
D
A
while!infile.eof()
循环中的count
中,该计数器是数组索引)。 - Ken White