Opening and closing files...
Ok, so I have an assignment to open 1 file, get the data, close it, then open 2 more files and pull the data from those as well.
my first file opens perfectly fine,but then the second and third files show a bunch of nonsense that was entered into my variables...
is there anything wrong with my code that anyone can notice?
1 2 3 4 5 6 7 8 9 10 11 12 13
|
inData.open("store1.txt");
inData >> store1info1 >> store1info2 >> store1info3 >> store1info4 >>
store1info5 >> store1info6;
inData.close();
inData.open("store2.txt");
inData >> store2info1 >> store2info2 >> store2info3 >> store2info4 >>
store2info5 >> store2info6;
inData.close();
|
I've defined the fstream as inData already, and it works fine, the first file opens correctly, but the second is the one that is having issues.
Last edited on
I suspect that the fail bit is being set from the first file. (Does store1info6 have the correct value?)
You can fix it by using:
1 2
|
inData.close();
inData.clear();
|
but a better way would be to use a separate file stream object for each file:
1 2 3 4 5 6 7 8
|
{
ifstream inData( "store1.txt" );
inData >> store1info1 >> ...;
}
{
ifstream inData( "store2.txt" );
inData >> ...;
}
|
The best way, however, would be to make yourself a function that gets the info.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct StoreInfo
{
int number;
string manager_surname;
double daily_sales;
...
};
StoreInfo readStoreInfo( const string filename )
{
StoreInfo result;
ifstream inData( filename.c_str() );
inData >> result.number
>> result.manager_surname
>> result.daily_sales
...
return result;
}
int main()
{
vector<StoreInfo> stores;
for (int i=1; i<=3; i++)
stores.push_back( readStoreInfo( string( "store" ) +(char)(i +'0') +".txt" ) );
...
}
|
Hope this helps.
Last edited on
Topic archived. No new replies allowed.