Reading lines of characters separately into arrays and comparing answers C++

45 Views Asked by At

I have done a project where I read only 1 line of 20 characters and compare those characters to an answer key and outputs how many are right and how many are wrong based on what they inputted in the file. My code below shows how it looks with just one line of 20 characters in the .dat file. I would like to do the same thing like this, but with 7 lines of 20 characters each. I am not sure what to write to separate the 7 lines and compare them separately to the right answers.

    char letter;
    int index = 0;

    while (inData >> letter) // takes the character from each array from the file
    {
        studentAns[index] = letter;
        index++; // takes the 20 characters from the file
    }

I have tried to add more variables outside, and inside the loop, but the output displays nothing. Such as this.

# Correct | # Incorrect
-----------------------
    0     |    20
-----------------------

You failed!

char letter;
char letter2;
int index = 0;
int index2 = 0;

while (inData >> letter) // takes the character from each array from the file
{
    studentAns[index] = letter;
    index++; // takes the 20 characters from the file
    
    while (inData >> letter2) 
    {
        studentAns2[index2] = letter2;
        index2++; 
    }
}

    
2

There are 2 best solutions below

0
PaulMcKenzie On

If you can guarantee 7 students with 20 questions each, then you can use a two-dimensional array of char to perform the input:

char student[7][20];

while (int studentIndex = 0; studentIndex < 7; ++studentIndex)
{
    for ( int letterIndex = 0; letterIndex < 20; ++letterIndex)
        std::cin >> studentAns[studentIndex][letterIndex];
}

Then student[0][0] would be the first question of the first student, student[0][1] would be the second question of the first student, student[1][3] would be the fourth question of the second student, etc.

0
ritz092 On

I will give you a more general answer to the question you have asked. Suppose you have a file which contains "n" number of lines and each line is of variable length. Then we will take the help of vector and getline() function to get the answer.

#include <iostream>
#include <fstream>
using namespace std;

int number_of_lines = 0;

int main(){
    string line;
    vector<string> str;
    ifstream myfile("example.dat");
    if(myfile.is_open()){
        while(myfile.peek() != EOF){
            getline(myfile,line);
            str.push_back(line);
            number_of_lines++;
        }
        myfile.close();
    }
    for(int i=0; i<number_of_lines; i++)
    {
        cout<<str[i]<<endl;
    }
    return 0;
}