I have a text file in the following format:
100 #gravity
5000 #power
30 #fulcrum
I want to assign these values to named variables, like so:
void Game::reloadAttributes()
{
float test1, test2, test3;
string line;
std::fstream file;
file.open("attribs.txt");
if (file.is_open()) {
cin >> test1;
file.ignore(50, '\n');
cin >> test2;
file.ignore(50, '\n');
cin >> test3;
file.ignore(50, '\n');
file.close();
}
else
{
cout << "\n****Couldn't open file!!****\n" << endl;
}
cout << ">>>> " << test1 << ", " << test2 << ", " << test3 << endl;
}
Of course, these aren't destined for the local test variables, but in fields belonging to the Game class, just using these to test its reading correctly. The program just hangs at cin >> test1. Ive tried using getLine(file, line) just beforehand, that didnt work. What am I doing wrong? Cheers
CodePudding user response:
You're using cin
instead of file
for your input lines.
Instead of cin >> test1;
, do file >> test1;
. Then it should work fine.
CodePudding user response:
An object of type istream
(in this case cin
) takes user input. So of course the program will wait for you to input a value and then store it inside test1
, test2
, and test3
respectively.
To fix your issue, just replace cin
with file
as such:
file >> test1;
file.ignore(50, '\n');
file >> test2;
file.ignore(50, '\n');
file >> test3;
file.ignore(50, '\n');
file.close();
Output:
>>>> 100, 5000, 30