This problem is because you're overwriting the same space and (most importantly), you're only storing one line.
Look carefully at lines 30 to 40.
What actually happens:
-You allocate a string that has the same number of characters as there are lines
--This is okay, but it probably wouldn't end well if your file only had three lines or less.
-Within your loop, you assign the
pointer temp to s[count].
--Now, the important thing to note here is that temp itself is never changed, therefore all of the elements in your array s are actually pointing to the same exact spot.
-The fact that temp never changes also creates another problem.
--You read in the line and store it in the array temp points to, but since you're reusing the same array, you're overwriting the old data.
What you can do is actually allocate new memory with each iteration:
30 31 32 33 34 35 36 37 38 39 40
|
infile.seekg(0);
while (infile.good())
{ //Start each iteration with a fresh, new array
char *temp = new char[150];
infile.getline(temp, 150, '\n');
s[count] = temp;
count++;
}
|
Another issue is that you forget to free the memory at the end of the program. When you allocate memory, you are requesting space to be reserved for your data. That means nothing else is allowed to touch it. However, it is also your responsibility to tell the computer that you're done with it, otherwise it will continue to sit as reserved memory. (Actually the OS is probably smart enough to clean up all the memory when the program is over, but don't depend on the OS to do your work!)
Not freeing your memory is known as a "memory leak".
62 63 64 65
|
//Be careful with this. Only use this specific code if you've added some code to
// initialize temp with null pointers
for(unsigned i(0); i < 100; ++i)
delete[] temp[i];
|
Extra information (you don't have to read this):
Normally, I'd say this allocation is not needed, because you have no way of knowing how long the line will be (unless you go crazy with rereading each line), so it'd probably be sufficient for you to do:
1 2 3
|
char temp[150] = "\0";
infile.getline(temp, 150, '\n');
s[count] = temp;
|
However!... There is one major issue if you attempt to use the above code. The types of s and temp no longer match.
Type of s[count] == char*
Type of temp == char[150]
|
The compiler probably and will spit out an error message.
Lets take a look at line 58, where you actually declare your original array:
There is actually a very big difference between that and this:
Here's the difference:
-The first is an array of pointers
-The second is a pointer to an array
Now this really comes down to intention. When you declared temp on line 58, what was that 100 for? Is it supposed to the maximum number of strings you want to hold? Or is it supposed to be for the maximum size of your individual strings? In other words, do you want to hold an array of 100 strings whose sizes are unknown or hold an array of strings 100 characters long?