There are numerous things in your code that give me pause:
1) You dynamically-allocate an array of ints (stored in "ptr") for each while-loop iteration and you give each index a value (its index number squared) but the you don't do anything with this array of its indeces. Are you just practicing, or did you forget something?
2) You need a "delete[] ptr" call within the while loop, somewhere after the assignment to "new[]" otherwise when the while loop iterates again, you lose your handle to the old array, but it stays allocated and you get a memory leak.
3) Your "delete[] ptr_array" call need to go! As ptr_array was not dynamically allocated using new[], its in the static storage area (where all global variables are).
4) The reason the last name in your file prints twice is b/c your check for EOF occurs at the beggining of the loop. After the last name is read in with "name >> name1" (the file is at EOF, but no read past that was made, so the stream has not signaled its EOF state) it is printed on the console. The check in the while produces true, so another iteration occurs. This time "name >> name1" fails to read in a name, sets the EOF state in the stream, and "name1" still contains its previous contents ("Cameron") which is promptly printed again.
The solution is to check for EOF *after everytime* a name is read in. Altho some people dislike this stylistically, I prefer it because it involves less repeat code (having only 1 "name >> name1" statement in your while instead of 2, one in your while and one preceeding it), and is not *totally* unstructured b/c it simply means the condition driving the loop occurs in the middle of the loop, not at the beginning:
1 2 3 4 5 6
|
while(true) { //Infinite loop?? Nonesense!
name >> name1;
if (!name) //Since EOF is whats being tested could use "if (name.eof())" if preferred.
break;
cout << name1 << '\n'; //Avoid endl for a newline, it messes with cout's internal buffer and slows it down. Just pass a '\n' char instead.
}
|