Hello I need to read 50 intergers from a text file and put them into an array. and output or show the user the numbers.
for example: 23 73 58 49 34..... I need them to go into my array.
I tried this code but it just outputs -850993.

Heres my code :

int main ()
    ifstream infile;
    int num;
    int list[50];

while (!infile.eof())

    system ("pause");
    return 0;

5 Years
Discussion Span
Last Post by rodrigo.l.salazar.14

well I didnt give it a value

Bingo. So the actual value it has is whatever random garbage was in that memory location. Chances are extremely good that you're indexing the array out of bounds.

I just thought that num would be the numbers I am reading from the file.

That makes no sense at all. num is used to index the list array. It's the array that holds the numbers you're reading from file, so I'd expect something like this:

int num = 0;

// Read up to 50 numbers from the file
while (num < 50 && infile >> list[num])

// Display the read numbers
for (int i = 0; i < num; ++i)
    cout<< list[i] <<'\n';

Your loop should look like this

for(int i=0; i < 50; i++)
    infile >> list[i];
    cout << list[num];

You also dont need to put it in a while loop if you know you are only going to read 50 records. If you dont know how many records you need to read than you wan use a while loop like this.

int i = 0;
while(infile >> list[i])
    cout << list[i];
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.