我有 4 天的 C++ 培训,所以请耐心等待。
评估多项选择题考试需要两个数据文件。第一个文件 (booklet.dat)包含正确答案。总题数为 50 题。 样本 文件如下:
ACBAADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD
第二个文件 (answer.dat) 包含学生的答案。每行有一名学生 包含以下信息的记录:
学生的答案(共50个答案),格式与上述相同(*表示无答案),后面是学号和学生姓名。示例:
AACCBDBC*DBCBDAAABDBCBDBAA*BCBDD*BABDBCDAABDCBDBDA 6555 MAHMUT
CBBDBC*BDBDBDBABABABBBBBABBABBBBD*BBBCBBDBABBBDC** 6448 SINAN
ACB*ADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD 6559 CAGIL
我有一个作业要编写一个 C++ 程序,该程序会计算每个学生的正确答案总数,并将此信息输出到另一个名为 report.dat 的文件中。在此文件中,必须提供学生的 ID、姓名和分数。每个正确答案得 1 分。对于上面给出的示例文件,输出应如下所示:
6555 MAHMUT 10
6448 SINAN 12
6550 CAGIL 49
这是我到目前为止所拥有的:
include <iostream>
include <fstream>
using namespace std;
int main()
{
char booklet[50] answers[50]
int counter
// Link answers with booklet.dat
booklet = ifstream
input_file("booklet.dat");
return 0;
// Link answers with answers.dat
answers = ifstream
input_file("answer.dat");
return 0;
while (booklet==answers)
{
counter++
cout << "The student had">>counter>> "answers right";
}
}
我什至不确定我的方向是否正确。我知道我需要从文件 booklet.dat 创建一个数组,并从文件 answer.dat 创建另一个数组。然后必须进行比较并计算两者之间的匹配。
我不期望任何人为我做作业,我只需要在正确的方向上插入。
最佳答案
1.) 在你的语法上:
a) C++ 中的每一行都必须以“;”结尾。您的示例中有些行没有。 (通常您的编译应该指向此行或下一行,但会出现错误)
b) 多个变量定义需要在两个不同变量之间使用“,”。
2.) 我建议您使用类似的东西: (看看 C++ Reference fstream ) 编辑:只是一个小纲要,这种形式并不完整,只是为了给您和想法;-)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int nr_of_students = 1000; /* Or any number you'd like to analyze */
int stud_nr[nr_of_students];
string stud_name[nr_of_students];
int stud_count[nr_of_students];
fstream in_out;
in_out.open("filename.dat",fstream::in); // fstream::in for reading from file
// fstream::out for writing to this file
if(in_out.is_open())
{
for(lines=0;(in_out>>answers && lines<nr_of_students);lines++)
{
in_out >> stud_nr[lines]; /* EDIT: sorry hat some index confusions here... */
in_out >> stud_name[lines];
stud_count[lines]=0;
for(int i=0;i<50;i++)
{
/* comparison between the booklet_array and the answers_array */
/* Count up the stud_count[lines] for each right comparison */
}
}
/* some simmilar code for the output-file */
}
else cout << "Error reading " << "filename.dat" << endl;
return 1;
}
3.) 使用 vector ,您的代码还将获得更高的性能。 一个好的教程是:Tutorial part I 你可以在评论中找到第 2 部分
4.) 您可以使用 argc 和 argv** 实现更动态的代码,只需 google 即可
我希望这些评论能帮助您继续下去;)
关于c++ - 在 C++ 中使用外部文件创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18120197/