I was practising with the past year questions for tomorrow's final exam.

I wanted to read who has the highest score and show the highest score from the text file (see attachment).

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

ifstream infile;

int main()
{
    const int x = 3;
    char *name[x]; // Student's name
    int score[x]; // Student's score
    int i; // Counter
    int max; // Highest score
    int min; // Lowest score

    infile.open("score.txt");
    if (!infile)
    {
        cout << "Cannot find file. The program terminates." << endl;
    }

    while (infile)
    {
        for (i = 0; i < x; i++)
        {
            infile >> name[i];
            infile >> score[i];
        }
    }
    infile.close();

    max = score[0];
    min = score[0];

    for (i = 0; i < x; i++)
    {
        if (score[i] > max)
            max = score[i];

        else if (score[i] < min)
            min = score[i];
    }

    cout << name[i] << " got the highest score of " << score[i] << endl;
    system("pause");
    return 0;
}

Everytime, my program produces many errors, and keep getting pop-up boxes.

char *name[x];

This creates an array of char pointers. Each one is pointing to some random place in memory.

infile >> name[i];
This is an attempt to write over than random place in memory. Writing over some random place in memory is very very bad.

If you make a pointer, you need to make it point at something. Alternatively, just make an array of proper C++ string objects and use them.

cout << name[i] << " got the highest score of " << score[i] << endl;
This makes no sense. Shouldn't you be outputting the name and score of the person with the highest score? At this point, you have not set i to anything meaningful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.