I'm opening a file in a main function. I want to pass this file to a few functions but it looks like a first called function is clearing this file. This is a file:
1 5 6 8
6 5
1
2 6 8
6 7 5 1 2 4
First function counts lines in file. Second function counts the number of individual numbers.
int countTransactions(ifstream &dataBaseFile) {
int numOfTransactions = 0;
string line;
while(getline(dataBaseFile, line))
numOfTransactions++;
cout << "countTransaction" << endl;
cout << numOfTransactions << endl;
return numOfTransactions;
}
void countItems(ifstream &dataBaseFile) {
map<int, int> items;
map<int, int>::iterator it;
int item;
while(!dataBaseFile.eof()) {
dataBaseFile >> item;
it = items.find(item);
if(it != items.end()) {
it->second++;
continue;
} else items.insert(make_pair(item, 1));
}
for(it = items.begin(); it != items.end(); it++)
cout << it->first << " => " << it->second << endl;
}
int main() {
ifstream dataBaseFile("database3.txt", ios::in);
if(!dataBaseFile.good()) {
cout << "Failure while opening file";
exit(1);
}
countItems(dataBaseFile);
countTransactions(dataBaseFile);
dataBaseFile.close();
}
This is an output:
countTransation
5
countItems