Hi im trying to create a code where it would read from a separate text file some names and grades, then display them. However i am asked to use a class to "store"(if thats the word) them as below:

#include <iostream>
#include <fstream>
using namespace std;
class student
{
      private:
               string name;
               string model;
               int price;

      public:
             void display(student a);
             void grade();
};



void student::display(student a) 
{
    cout<<a.name<<" "<<a.model<<endl;
    cout<<"score: "<<a.price<<endl;
    cout<<" "<<endl;
}



int main(){
    student end;
    int count=0;
    student prods[100];
    ifstream infile;
    infile.open("C:\\students.dat");
      while(infile.peek()!=EOF) {
       infile
       >>prods[count].name
       >>prods[count].model
       >>prods[count].price;
       count++;
      }
    infile.close();

    for(int i=0; i<count; i++)
     end display(prods[i]);

    system("pause");
    return 0;
}

when using a "struct" style. it computes effectively and reads out fine. However i am unable to do this using the class as there is errors saying "the string name is set to private". any help is much appreciated.

Recommended Answers

All 2 Replies

Aside from the obvious disconnect between the stated goal of having a students name and grades as member variables for the class rather than name, model, price as member variables, the answer is classes default member variables and methods to private access whereas structs default member variables and methods to public access. That means you have two options. You can either declare the class variables and methods using public access, or, preferably, you can let the member variables be private and declare and define public methods to access and change the variables. The methods to do that are often called something like setName or getNaame to make it obvious what action is intended for which variable. A method to display all desired member variables is often useful, whether it's called display or whether you overload the >> operator (but I suspect you haven't come across operator overloading yet, so go with display).

commented: helped nicely +0

i used public access and it worked well. thank you very much. i also found out little erroes which ive also fixed up/improved.

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.