0

I have been debugging this simple c++ program for hours but I cannot figure out why it writes garbage values in to text file.

when I use fwrite to write data struct to "users.txt" file it looks like this after the program exited.

Dan ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌTest ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌTEST ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ4 ÌÌÌÌÌÌÌÌÌÌÌ TEST ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌTEST ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ

This is the related code

struct student {

    int i_number;


        char first_name[50], last_name[50];
        char Address[75];
        char Date_Inquiry[11];
        int Tp;
        char Qual[100];
        char Email[50];
        int Age;

    };

struct student e;
recsize = sizeof(e);
fp = fopen("users.txt","w+");
another ='Y';

            while(another == 'Y' || another == 'y')

            {

                  system("cls");

                cout << "\n";

                cout << "\t INQUIRE NUMBER : ";

                cin >> e.i_number;

                cout << "\n\t FIRST NAME : ";

                cin >> e.first_name;

                cout << "\n\t LAST NAME : ";

                cin >> e.last_name;

                cout << "\n\t DATE OF INQUIRY : ";

                cin >> e.Date_Inquiry;

                cout << "\n\t ADDRESS : ";

                cin >> e.Address;

                cout << "\n\t CONTACT NO : ";

                cin >> e.Tp;

                cout << "\n\t QUALIFICATION : ";

                cin >> e.Qual;

                cout << "\n\t EMAIL : ";

                cin >> e.Email;

                cout << "\n\t AGE   : ";

                cin >> e.Age;


                fwrite(&e,recsize,1,fp);



                fflush(stdin);

                cout << "\n Add Another Record (Y/N) ";
                another = getchar();


            }

 fclose(fp);

please could you give me hints to figure out what's going on ?

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Dan Jay
  • 874
  • 10
  • 27
  • 1
    Not sure this has much to do with padding. You're dumping the whole structure in a file. Some of the arrays are quite longer than what you put in them: "Dan" has four bytes, including a terminating 0, but `first_name` has 41 more bytes. Those will be garbage. – isanae Dec 15 '15 at 08:50
  • thank you for the tip @isanae – Dan Jay Dec 17 '15 at 09:09
  • No problem. And of course by "41 more bytes" I mean "46 more bytes": `first_name` is an array of 50 characters and you're using 4 of them. I think I confused 50 and 75 and thought `first_name` was a `char[45]`. – isanae Dec 17 '15 at 18:52

0 Answers0