devxlogo

Program compiles but does not show age data

Program compiles but does not show age data

Question:
I’m anxious to know why my program is notdisplaying the data, yet it compiles perfectly.

I want to read this struct; in particular: age. Ihave two sets of code that I have tried. Neitheris reading the file properly ? they give megarbage,yet they both compile.

My file for age looks something like this:

45 12 14 

Answer:
In C/C++, a program compiling has nothing to dowith whether or not it may run safely orcorrectly.This is true of most compiled languages, but Cand C++ do not try to interfere with the user’sintentions, hence no attempts are made to check validitiesof your program at run time.

That’s your main problem ? the file you createdfor age is a text file and you are trying toread in till the sizeof(int). This will not work because thedata in your file do not correspond to the sizeof int.

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

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

**/#include #include 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;}

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist