1

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

gymcode
  • 3,955
  • 13
  • 55
  • 110
  • What is the question here, exactly? Looks like you have a skeleton set up, now you just need to keep working on it... – jmc May 20 '18 at 09:36
  • I am not sure what is my next step. How can I go about storing each value from the string of text into a variable? I can work on the writing of the new variables in the new text file after that. – gymcode May 20 '18 at 09:38
  • EDIT: can't seem to place code blocks in a comment, so I'll move it to an answer. – jmc May 20 '18 at 09:40
  • Next time, search the internet for "c++ read file struct" for examples. Search the internet first. – Thomas Matthews May 20 '18 at 16:23

2 Answers2

1

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.

Gameerik
  • 5
  • 4
0

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.

jmc
  • 540
  • 3
  • 10
  • `while(infile.good())` tests before reading and using the data read. You need to test after the read and before using otherwise you run the risk of the read failing and the program processing garbage. Similar to https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 May 20 '18 at 10:43