-1

I am trying to read full names that are separated by space from a file. In the example, name student. Here is my code:

class student{
    string name;
    int degree;
    int stage;
public:
    void input(){
        getline (my_file,name);
        my_file>>degree;
        my_file>>stage;
    }

    void display(){
        cout<<name<<"\n"<<degree<<"\n"<<stage<<endl;
    }
};

int main()
{
    student S[3];
    int len=0;
    my_file.open("D:/h.txt", ios::in);
    if (!my_file) {
        cout << "No such file";
    }
    else
        while (!my_file.eof()) {
            S[len].input();
            len++;
        }
    for(int i=0;i<3;i++)
        S[i].display();
    my_file.close();
    return 0;
}

my "h.txt" file:

jack Donald
58
5
David William
82
4
Anthony Mark
89
3

My problem is, it don't show anything.

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jack556
  • 1
  • 1
  • 1
    Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please [edit] your question to actually ask a question, and give us details about what's wrong with the code you show us. – Some programmer dude May 18 '22 at 07:03
  • You should use function parameters. Also take a look at [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – 273K May 18 '22 at 07:04
  • Also look at [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/) – Remy Lebeau May 18 '22 at 07:56
  • @RemyLebeau Thanks, I solved it in the previous article – jack556 May 18 '22 at 08:10

1 Answers1

0

Refer this:

    void input() {
        getline(my_file, name);
        string blah;

        getline(my_file, blah);
        degree = std::stoi( blah);

        getline(my_file, blah);
        stage = std::stoi(blah);

    }
zpc
  • 47
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 19:40