Reputation: 4623
data.txt
contains the following information: firstName
, lastName
, salary
, increment
.
James Chong 5000 3
Peter Sun 1000 5
Leon Tan 9500 2
I want to read data.txt
, make the necessary calculations, and store the output of 3 variables in anewData.txt
:
firstName
, lastName
, updatedSalary
(salary
*percentageIncrement
)
I only managed to proceed to reading and display information in data
.
Below is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string filename = "data.txt";
ifstream infile;
infile.open(filename);
//if file cannot open, exit program
if (!infile.is_open()){
exit(EXIT_FAILURE);
}
string word;
infile >> word;
while(infile.good()){
cout << word << " ";
infile >> word;
}
system("pause");
return 0;
}
May I know are there any references that I can make use of? Thank you
Upvotes: 1
Views: 1196
Reputation: 5
I am not entirely sure about the question , but you might find substr function useful (if you need to process the data),about writing to a file, you can just create an ofstream output("newData.txt") and simply write the result there. (output << result). Also there is a tokenizer library in BOOST if you don't want to solve it with substr.
Upvotes: 1
Reputation: 538
You're expecting each line to have 4 words separated by whitespace, so it's as easy as extracting them from infile
at each iteration:
while(infile.good()) {
string first_name, last_name;
infile >> first_name;
infile >> last_name;
unsigned int salary, increment;
infile >> salary;
infile >> increment;
}
of course you should check that infile
is good after attempting to extract the various pieces, should the lines be malformed.
You can get fancier here, but this covers your basic needs.
Upvotes: 0