Reading txt file into Array

I'm doing a bubble sort program, but I don't need help with the algorithm. However, I do need help reading a txt file into an array. The file is a bunch of double values of unknown amount (But less than 1000 items), like:

1.023
1233
532.9
etc...

I plan to pass the file through input redirection. (prgm.exe < data.txt) So, I want the for loop to stop once it reaches the end of the file. My attempt so far, that I know doesn't work:

1
2
3
4
5
6
7
double d[1000];
int size;
for(int i = 0; i < 1000; i++)
{
   cin >> d[i];
   size++;
}
The problem is your loop will keep going til 1000 even if your file has less which will give you wonky* numbers.

My suggestion is to either use a infile.eof with a break statement:

I.E.
1
2
3
4
5
6
7
8
9
10
...
for(int i = 0; i < 1000; i++)
{
   if (infile.eof == true) 
   { 
       break;
   }
   infile >> d[i];
   size++;
}

Or something of that ilk.

Of course you could have a cin statement and the user input the amount of data they want inputted from your file.

I.E.
1
2
3
4
5
6
...
cin >> size;
for(int i = 0; i < size; i++)
{
   infile >> d[i];
}


or similar.

*= scientific term

EDIT:
I just noticed that your code is using cin statements instead of infile(or whatever command you chose) that could be your issue
Last edited on
Topic archived. No new replies allowed.