Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Mar 27, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Program compiles but does not show age data

I'm anxious to know why my program is not displaying the data, yet it compiles perfectly.

I want to read this struct; in particular: age. I have two sets of code that I have tried. Neither is reading the file properly — they give me garbage, yet they both compile.

My file for age looks something like this:


In C/C++, a program compiling has nothing to do with whether or not it may run safely or correctly. This is true of most compiled languages, but C and C++ do not try to interfere with the user's intentions, hence no attempts are made to check validities of your program at run time.

That's your main problem — the file you created for age is a text file and you are trying to read in till the sizeof(int). This will not work because the data in your file do not correspond to the size of int.

The code with the char array works because the size of char is the same in binary as it is in ASCII. In other words, a char string has the exact same representation for both binary and ASCII representations.

Here is a simple example of how you can get around your problem:


struct team{
char name[15];
int age;

int main(void)
        team Teams;

        ifstream fout("age.dat");
        while(fout >> Teams.age)
                cout << Teams.age << endl;

        return 0;
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date