-

2011年8月4日星期四

How do I make a C++ program input data from a file?

-I have a working payroll program but I need to add code to make it calculate the pay rate from a .dat file.

I tried to add <fstream> but I didn't know how to combine it with my code, where do I put it, and how does it know which part of the file to read?



Here is my code:

#include <iostream>

#include <iomanip>



using std::cout;

using std::cin;

using std::endl;

using std::fixed;

using std::setprecision;



int main()



{



double hours = 40.0;

double rate = 10.0;

double gross = 0.0;

double overtime = 1.5;





cout << "Enter the ammount of hours worked: ";

cin >> hours;

cout << "Enter the ammount paid per hour: ";

cin >> rate;



if (hours<0 || rate<0)



cout << "ERROR pick a different number" << endl;



else



if(hours > 40){ //calculate gross pay

overtime = (hours-40) * rate * 1.5;

gross = 40 * rate + overtime;



}



else

{

gross = rate * hours;

}



cout << "Overtime: " << overtime << endl;

cout << "Gross pay: " << gross << endl;



system ("pause");



return 0;



}i have posted its answer in one of ur previous questions.-

http://answers.yahoo.com/question/index;鈥?/a>First of all, add #include <fstream> in the beginnng

Second of all, so that the program knows what part of a file to read, you must get a line, then tokenizer it.

An example here:

ifstream file;

file.open("filename.dat"); // if you want to use STD::string, add .c_str() after the filename var

string line;

getline(file, line);



Now tokenize the string.

Tokenizing is a whole different world though. I've recently made a tokenizer class extention to the standard library (as in for my own use), but I'm still in final-testing phase. If you have large tokenization problems you can email me, and I'll see if I can help.
Same answer as before....

没有评论:

发表评论