Struct and files C++

I'm trying to write some data from a struct to a file, however,the program will not let me enter any data in the struct, what is the problem?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# include <iostream>
# include <fstream>

using namespace std;
int size (fstream & myfile)
{
     int length;
     / / GET LENGTH OF FILE:
     myfile.seekg (0, ios :: end);
     length = myfile.tellg ();
     myfile.seekg (0, ios :: beg);
     return length;
}
struct Student
{
     short number;
     string name, course;
     float note1, note2;
};

int main ()
{
     int length, a, op, tam;
     char * buffer;

     fstream myfile;

     myfile.open ("alunos.txt" fstream :: out);

     if (! myfile.is_open ())
     {
         cout << "Error opening file";
     }
     else
     {
         cout << "1 to register 2 to exit" << endl;
         cin >> op;
         switch (op)
         {
         case 1:

             Student a;

             cout << "\ nEnter number:";
                 myfile >> a.number;

                 cout << "\ nEnter name";
                 myfile >> a.nome;

                 cout << "\ nEnter course \ n";
                 myfile >> a.curso;


                 cout << "\ nEnter note 1 \ n";
                 myfile >> a.nota1;


                 cout << "\ nEnter note 2 \ n";
                 myfile >> a.note2;

                 myfile.close ();
                 break;

         }

     }

     return 0;
}
Last edited on
closed account (Dy7SLyTq)
you first have to give student.* a value to write to file
Your program won't compile.

Your comment at line 8 is defective.

The spelling of the members of your struct does not match the references at lines 45-55.

Lines 45-55, You're trying to read from myfile (>>) into members of your struct. If you want input from the user via the console, you have to use cin.

Once you read the input from the user, then you can write it to myfile using the output openerator (<<).
Thanks, already solved the problem.
Topic archived. No new replies allowed.