#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
ifstream theFile("players.txt");
int id;
string name;
double money;
while (thefile >> id >> name >> money ){
cout << id << ", " << name << ", " << money << endl;
}
}
Text file:
1 Brad 146
2 John 654
3 Mark 454
Firstly, your condition in the while loop won't work as you expect. The extraction operator >> returns a reference to the stream (thefile in this case), and will always return that reference even in cases of failure. Instead use a function that checks the state of the stream, such as while (thefile.good()). As for your actual question, what exactly are you asking? If you only want to print data for one player then just perform the extraction once and get rid of the loop. I doubt this is what you mean though.
Advice : working with data from textfiles by means of streaming directly from them will always prove to be expensive operation escpecially as the records get large, I would advice you to load your file into ram maybe into a vector or an array of structs then operate on them while they are in memory, that will significantly reduce the latency induced by disc IO.
struct player
{
player(int id, string nm, double mny):Id (id), Nane (nm), money (mny){}
int Id;
string Name;
double money;
};
vector<player> records;
void load (vector<player>& vec)
{
ifstream in ("players.txt");
if (! In) {std::cout <<" couldn't open your file "; return; }
int id; double csh; string name;
while (in>> id>> name>> csh)
{
vec.push_back (player (id, name, csh));
}
}
///use your vector now.
@Modshop AFAIK streams do provide implicit Boolean type conversions that allow you to enquire about the stream state by checking the currently set bits {goodbit, badbit, failbit,...) so I believe his while condition should work as expected.