Click here to Skip to main content
15,399,959 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I create a dynamic array to read the contents of the file into the dynamic array using a suitable loop.
Then, Using a second loop, display the contents of the array in the following format:
o Allocate 30 spaces for the entire name
o Allocate 15 spaces for the student ID
o Allocate 5 spaces each for the test score

What I have tried:

Student* stud;
int a;

ifstream inFS;
inFS.open("student.dat", ios::app);
if (!inFS.is_open()) {
    cout << "Could not open file student.dat" << endl;
    exit(1);
}
    Student* Stu_list = new Student[];

    inFS.close();
Posted
Updated 17-Nov-21 20:19pm
Comments
Rick York 18-Nov-21 0:51am
   
Your question is unclear. Can you use an STL collection like a std::list to hold the items? Do the three items you listed have to be dynamically-sized or can the be static items? All of these things matter to how it is implemented.
Richard MacCutchan 18-Nov-21 4:13am
   
The first thing you need to find out is how many actual records are contained in the file. You can either read the file line by line counting it that way, or read the entire file into memory and find the individual records from the content in memory.

1 solution

If you can, use the std::vector container, that automatically grows.
On the other hand, if you have to manually craft your own dynamic container, then you should
use realloc (see, for instance Use of realloc() in C[^]).
See, as pointed out by k5054 C Language: realloc function (Resize Memory Block)[^], instead.
   
v2
Comments
k5054 18-Nov-21 9:41am
   
Except don't use that example, as it has a bug. In particular, if realloc() can't allocate new memory, it returns NULL, and does not change the contents of what was pointed to. So in the expression ptr = realloc(ptr, newsize), if no memory is available, then ptr gets set to NULL, and you've lost the handle to the memory you have allocated. Take a look at https://www.techonthenet.com/c_language/standard_library_functions/stdlib_h/realloc.php instead
CPallini 18-Nov-21 10:50am
   
You are completely right.
Thank you for pointing it out.
k5054 18-Nov-21 11:11am
   
I was surprised at how many web resources make the same mistake. It took checking several links to find a correct one. That being said, I guess it should be pointed out that given modern hardware, the likelihood of realloc failing is quite small, particularly in a small program in 64-bit mode where your virtual memory is on the order of 256TB. But that doesn't excuse sloppy programming!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900