Here is an example that works, i won't really understand why your code ain't working coz the snippet you gave above isn't enough to deduce the cause of errors, if you could provide the entire code that would be simpler to point out your errors however i can manage to give you some hints on what you can check on.
1. make sure the file is accessible to your program.
2. check if your file was successfully opened.
3. use your stream to control your loops it's better, your might not know before hand if
you've enough info in your file to fill your array .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream in("file.txt");
if(!in){cerr<<"file not found\n"; return(1);}///check stream
string data,arr[5];
size_t index=0;
while(in>>data&&index<5)///your file must atleast contain 5 records
{
arr[index]=data;
cout<<arr[index]<<endl;
++index;
}
}
|
Am not sure if there is a speed aspect that will matter in your loops however different loops will suit perfectly different applications, for example:-
1. for loops are mostly used when the number of iterations are already know before
your program is executed.
2. while loops are mostly used when your are not sure of the number of iterations
required during program execution.
however i believe if your execute them on exactly equal number of iteration the differences in their execution time might be totally negligible.
hope that helps.