2014-04-16 29 views
0

好的,所以我知道你们不是我自己的个人程序员,但我想知道你们是否可以在这里帮我一把。我在上学的时候担任教师助理。我知道一些C++,并试图制作一个基本程序来检查答案。使用数组获取测试结果

该程序的第一部分工作正常,以测试对关键的答案,但第二部分是我遇到的问题。我试图找出有多少学生回答了什么问题,因此我不必手工计算,但我似乎无法解决这个问题。

我真正需要的是能够打印出来,像这样:

问题A B C dé

等。

我知道我可能会需要一个嵌套的for循环,但我一直在这一整夜敲我的头。任何帮助,将不胜感激。

#include "stdafx.h" 
#include <fstream> 
#include <iostream> 
#include <iomanip> 
#include <string> 

using namespace std; 

void main(){ 

int numstud=0, numcorrect, i; 
string key, id, responses; 
ifstream keyfin, studfin; 
keyfin.open("answers.dat"); 
studfin.open("tests.dat"); 

keyfin >> key; 
studfin >> id >> responses; 

cout << setw(5) << "Student-Id's" << setw(20) << "# Correct" << endl << endl; 

while(!studfin.eof()) 
{ 
    numstud++; 
    numcorrect=0; 
    for(i=0; i<20; i++){ 

     if(responses[i] == key[i]) 
     { 
      numcorrect++; 
     } 
    } 

    cout << id << setw(20) <<numcorrect << endl; 
    studfin >> id >> responses; 

} 








studfin >> id >> responses; 
int col[20][5]={0}, j=0; 
char ch; 
studfin >> id >> responses; 
cout << "Question" << setw(10) << "A" << setw(5) << "B" << setw(5) << "C" << setw  (5) << "D" << setw(5) << "E"; 

while (!studfin.eof()) 
{ 
    for(i=0; i<responses.length(); i++) 
    { 
     col[i++][responses[i-'a'] ++]; 

    } 


} 
} 
+1

'void main'应该是'int main'和['while(!eof())'是错误的。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a -loop条件考虑的,是错误的)。 – chris

+0

你介意为什么更具体吗? – Skathix

+0

'col [i ++] [responses [i -'a'] ++]'< - 可能未定义的行为 – user657267

回答

0

就实现响应的直方图而言,您有一般想法。但是,行col[i++][responses[i-'a'] ++]有一些问题。

  • 首先假设responses较低的情况下,你可能是打算responses[i]-'a'而不是responses[i-'a'],以信等级转换为0,1,2,3,4指数。
  • 然后,它是您想要增加的表格的内容,而不是行和列索引。那是col[i][responses[i]-'a']++

作为便笺,您不需要第二个while (!studfin.eof())循环来更新直方图。您可以继续更新它,因为您正在检查对键的答案(除非在第一个循环结束时重置已达到文件结尾的输入流,否则不应该使用第二个循环)。