Using file stream in C++ to change sales.dat file. Help needed; thank you in advance.


How to pull the data from sales.dat and show the total sale and no sale using file stream c++? Any help will be appreciated. Thank you!?
I am trying to write a C++ program that reads file named “Sales.dat” which contains users and corresponding sales numbers.
"Sales.dat" contains following information which I typed in notepad and it is saved in same c++ project directory as Sales.dat

david 200
jhon 100
Andy Nill
Jim 50
Kim Nill



The program then should computes and prints the total sales from all users together as one and also print out user with no sales available.
The possible c++ program out put print should be like this on the command screen when you press ctrl + f5.

user total sale: 350
User with no sale: 2

but the following c++ program I wrote, I am getting same exact output like sales.dat with no user total sale and user with no sale.
david 200
jhon 100
Andy Nill
Jim 50
Kim Nill
Please help help ; how to manipulate the sales.dat to bring total sale and user with no sale.



#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <iomanip>

using namespace std;

int main ()

{

string filename = "prices.dat";
string line;
ifstream inFile;

inFile.open(filename.c_str());

if (inFile.fail())

{

cout << "\nThe file was not successfully opened"
<<"\n Please check that the file currently exist."
<< endl;
exit (1);

}
while (getline(inFile, line))
cout << line << endl;
cout << endl;
inFile.close ();
return 0;
}
Would this be better instead, first off?

while(inFile.eof() != true)

Second, you have to use the >> operator instead of getline(). Reason being, you need to read the name into strings and the sales into number variables in order to find the total sales.

getline() retrieves the entire line as a string, while the extraction operator reads one field of data at a time with whitespace as the delimiter.

Also, feel free to email me at sparkprogrammer@gmail.com.

Joe - C++ tutor



Topic archived. No new replies allowed.