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];

infile.open("infile.txt");
while (!infile.eof())
{   
for(i=0;i<50<<i++)
    infile>>list[num];i++;
    cout<<list[num];

}   
    system ("pause");
    return 0;

}

Recommended Answers

All 5 Replies

What's the value of num?

well I didnt give it a value I just thought that num would be the numbers I am reading from the file.

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])
    ++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];
    i++;
}

ahh! thanks to the both of you it works now thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.