-3

I have a text file with some data in it as shown below

Employee No.    Name        Rate per hour       Hours worked
100             Rishi         800                   40
101             Albert        700                   35
102             Richard       500                   30
103             Roni          600                   45
104             Reena         900                   40 

I need to display the emp no,name and salary now i managed to display the table exactly as it is i know to calculate the salary i need to multiply the rate and hours worked but my teacher told us to do it by ourselves

i only managed to display it as it is in the text file

#include <iostream>
#include<fstream>

using namespace std;


int main(int argc, char** argv) 
{
    char ch;


    ifstream inFile;
    inFile.open("C:\\Users\\dolej\\OneDrive\\Desktop\\assignment.txt");

    if (!inFile) 
    {
        cout << "Unable to open file";

    }

    while (!inFile.eof())
    {
        inFile >> noskipws >> ch;   //reading from file
        cout << ch;
    }

    inFile.close();

    return 0;
}
Rohun
  • 1
  • 2
  • Look into `std::istream::getline` and `std::stringstream` – Botje Jul 10 '19 at 09:51
  • 2
    _"but my teacher told us to do it by ourselves"_ Ahem.. – Lightness Races in Orbit Jul 10 '19 at 09:52
  • 1
    @Botje I would suggest to look into [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline) instead of `std::istream::getline`. – Algirdas Preidžius Jul 10 '19 at 09:53
  • Please take some time to read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Jul 10 '19 at 09:54
  • @LightnessRacesinOrbit he didnt explain anything on files so im trying to learn by myself – Rohun Jul 10 '19 at 09:54
  • 1
    Also please take some time to read [the help pages](http://stackoverflow.com/help), take [the SO tour](http://stackoverflow.com/tour), read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jul 10 '19 at 09:55
  • @Rohun So study and learn by yourself! So far you're asking us to do it.... – Lightness Races in Orbit Jul 10 '19 at 09:55
  • @LightnessRacesinOrbit i dont need someone to do it, i just need a guidance on how to do it – Rohun Jul 10 '19 at 09:56
  • Then you should talk to your lab assistant or professor to help guide you through it. Stack Overflow is a Q&A not for mentoring (though we do have chatrooms where you may get some help). Good luck! – Lightness Races in Orbit Jul 10 '19 at 10:00
  • @Rohun Then, you can try to learn by reading a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – Algirdas Preidžius Jul 10 '19 at 10:01

1 Answers1

0

There are roundabout 42 million solutions for your problem :-)

Let me explain what part of the code needs to be improved. The basic problem is that you read the input character by character. You should take advantage from the std::istream's ability to read whatver variable type that you want and for which an inserter operator >> exists. For nearly all build in types such an operator exists. So, if you want to read an int, then you can do that via int i{0}; std::cin >> i. Same with other type of variables.

Please read in a book about the iostream library.

Then there are other improvements. Always initialize all variables. Use uniform initializer {}. Initializing a std::ifstream can automatically open a file. It will be closed by the destructor automatically. Do not use while (!inFile.eof()). Use while(infile >> something) instead.

Then, as I said, read whole variables and not only one char.

Example easy solution:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <iomanip>

int main()
{
    std::ifstream infile{ "r:\\assignment.txt" };
    if (infile)
    {
        // Read the header line
        std::string header{};
        std::getline(infile, header);

        // Now we want to read all data in the text file
        // Define variables, where we will store the data
        int employeeNumber{ 0 };
        std::string name{};
        int ratePerHour{ 0 };
        int hoursWorked{ 0 };

        // Print the header
        std::cout << header << '\n';
        // Read all lines in a loop
        while (infile >> employeeNumber >> name >> ratePerHour >> hoursWorked)
        {
            // calculate the result
            const int salary{ ratePerHour * hoursWorked };
            // Print table
            std::cout << std::left << std::setw(16) << employeeNumber << std::setw(16) << name <<
                std::setw(16) << ratePerHour << std::setw(16) << hoursWorked <<
                "    Salary --> " << salary << '\n';
        }
    }
    return 0;
}

Then, since you are programmin in C++. Use Objects. Objects group related things together and defines methods to operate on the data. So you can define a class and with that a new data type. And becuase the inserter and extractor operator do not exist for this user specific type, you need to create them.

In your main, you can read the complete file in a simpel statement. Then calculate the result and the print it.

See:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <iomanip>

class Payroll
{
public:
    Payroll() {}

    void calculate() { salary = ratePerHour * hoursWorked; }

    friend std::istream& operator >> (std::istream& is, Payroll& p) {
        return is >> p.employeeNumber >> p.name >> p.ratePerHour >> p.hoursWorked;
    }
    friend std::ostream& operator << (std::ostream& os, const Payroll& p) {
        return os << std::left << std::setw(16) << p.employeeNumber << std::setw(16) << p.name <<
            std::setw(16) << p.ratePerHour << std::setw(16) << p.hoursWorked << std::setw(16) << p.salary;
    }

private:
    int employeeNumber{ 0 };
    std::string name{};
    int ratePerHour{ 0 };
    int hoursWorked{ 0 };
    int salary{ 0 };
};

int main()
{
    // Define variable and automatically open it.
    // Will be closed by destructor, when infile goes out of scope
    std::ifstream infile{ "r:\\assignment.txt" };

    // If the file is open ( !operator of ifstream is overlaoded )
    if (infile)
    {
        // Read the header line
        std::string header{};
        std::getline(infile, header);

        // Define a vector of Payroll. Use range the constructor of the vector to read all data from file
        std::vector<Payroll> payroll{ std::istream_iterator<Payroll>(infile), std::istream_iterator<Payroll>() };

        // For each payroll element in the vector of payrolls: Calculate the salary
        std::for_each(payroll.begin(), payroll.end(), [](Payroll & p) {p.calculate(); });

        // Output Result:
        std::cout << header << "    " << "Salary\n";
        std::copy(payroll.begin(), payroll.end(), std::ostream_iterator<Payroll>(std::cout, "\n"));
    }
    return 0;
}

Take your time and try to understand line by line . . .

Armin Montigny
  • 7,879
  • 3
  • 11
  • 29