user2905256
user2905256

Reputation: 145

Output from array is wrong

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>

using namespace std;

void make_array(ifstream &num, int (&array)[50]);

int main(){

ifstream file;  // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];


cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";

file.open(filename);

if(file.fail()){
cout <<  "The file failed to open.\n";
exit(1);
}

else{
cout << "File Opened Successfully.\n";
}


make_array(file, array);


file.close();

return(0);

}


void make_array(ifstream &num, int (&array)[50]){

int i = 0; // counter variable

while(!num.eof() && i < 50){
 num >> array[i];
 i = i + 1;
 }

for(i; i>=0; i--){
cout << array[i] << "\n";
}


}

Alright, so this it my code so far. When I output the contents of the array, I get two really large negative numbers before the expected output. For example, if the file had 1 2 3 4 in it, my program is outputting -6438230 -293948 1 2 3 4.

Can somebody please tell me why I am getting these ridiculous values?

Upvotes: 0

Views: 110

Answers (2)

Pradhan
Pradhan

Reputation: 16777

The check !num.eof() only tells you that the last thing you read was not eof. So, if your file was 1 2 3 4, the check will only kick in after the 5th num>>array[i] call. However, for that i, array[i] will be populated with a meaningless value. The only correct way to deal with eofs is to check for validity on every call to operator>>. In other words, the right condition is simply num>>array[i]. This works by exploiting this conversion to bool since C++11 and to void* pre-C++11.

Upvotes: 0

M.M
M.M

Reputation: 141648

Your code outputs the array backwards, and also it increments i twice after it has finished reading all the values. This is why you see two garbage values at the start. I suspect you are misreporting your output and you actually saw -6438230 -293948 4 3 2 1.

You end up with the extra increments because your use of eof() is wrong. This is an amazingly common error for some reason. See here for further info. Write your loop like this instead:

while ( i < 50 && num >> array[i] )
    ++i;

Now i holds the number of valid items in the list. Assuming you do actually want to output them backwards:

while ( i-- > 0 )
    cout << array[i] << "\n";

To output them forwards you'll need two variables (one to store the total number of items in the array, and one to do the iteration)

Upvotes: 3

Related Questions