Opening a file and outputting for function - c++

I have a code that I am doing and I got the basic version to work, I need help with how to implement a function in which the program reads a text file that I have saved and reads it and outputs it based on the function. Here is my code and what I have so far..
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//start main
int main()
{
double cost_merchandise, salary, yearly_rent, electricity_cost;
double totalCost, netProfit;
double PERCENTAGE_SALE = 0.15;
double PERCENTAGE_GOAL = 0.10;
double after_sale;
double Mark_up;
string line;
ifstream myfile ("F:/Intro To C++/ch0309.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
//gets data
cout << "Enter merchandise cost: ";
cin >> cost_merchandise;
cout << "Enter employee salary: ";
cin >> salary;
cout << "Enter yearly rent: ";
cin >> yearly_rent;
cout << "Enter the estimated electricity cost: ";
cin >> electricity_cost;
totalCost = cost_merchandise + salary + yearly_rent + electricity_cost;
//Output expenses, calculate mark ups, cost after 15%
cout << endl << setprecision(2) << fixed;
cout << "\nThe Company's expenses equals $: " << totalCost << endl << endl;
netProfit = cost_merchandise * PERCENTAGE_GOAL;
after_sale = netProfit + totalCost;
Mark_up = (after_sale - cost_merchandise) / 100;
cout << "A 10% profit is valued at $: " << netProfit << endl;
cout << "Mark Up is " << Mark_up * 100 << "%" << endl;
return 0;
}
//end of main

Here is a way to do it, assuming that your data is splited by whitespaced or new lines :
#include <string>
#include <vector>
#include <fstream>
template<typename T>
std::vector<T> getDataFromFile(const std::string& filename) {
std::ifstream file_input_stream(filename);
if (!file_input_stream)
throw std::exception("ifstream failed to open");
std::vector<T> data;
T input_data;
while (!(file_input_stream >> input_data).eof()) {
data.push_back(input_data);
}
return data;
}
and you use it like this :
auto int_vector = getDataFromFile<int>(filename);
// You can modify the template parameter with the good data type ( char, double, string... )
//To output the vector :
for (const auto& i : int_vector) {
std::cout << i;
}

Related

Getting data from every for loop

I want to output every data that I entered in the for loop in a tabular form. Unfortunately, the output only displays the last set of data that I entered. Any solution to solve this?
#include <iostream>
using namespace std;
int main()
{
double voltage, rpm, current, range;
int total; // total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin >> total;
cout << "\n";
for(int i=1; i<=total; i++)
{
cout << "Enter he voltage " << i << ":";
cin >> voltage;
cout << "Enter the current " << i << ":";
cin >> current;
cout << "Enter the rpm " << i << ":";
cin >> rpm;
cout << endl;
double range = (voltage*1.2) + (current*0.5) + (rpm* 0.2);
}
cout << "Voltage\t\tCurrent\t\tRPM\t\tRange\n";
for(int i=1; i<=total; i++)
{
cout << voltage << "\t\t" << current << "\t\t" << rpm
<< "\t\t" << range << endl;
}
return 0;
}
This variables
double voltage,rpm,current,range;
each can only store a single double. To store many doubles, use a std::vector<double>:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
int main()
{
std::vector<double> voltages;
int total; //total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin >> total;
cout << "\n";
for(int i = 1; i <= total; i++)
{
double voltage;
cout << "Enter he voltage " << i << ":";
if (cin >> voltage) {
voltages.push_back(voltage);
} else {
cout << "invalid input. Try again \n";
}
}
cout << "Voltage\n";
for (const auto& volt : voltages) {
cout << volt << "\n";
}
}
Instead of using many vectors you should use a data structure:
struct my_data {
double voltage;
double rpm;
double current;
double range;
}
And use a std::vector<my_data>.
Once you have that you should take a look at how to overload the input operator << for that data structure. But one thing at a time ;).
PS Don't use spaces so sparingly. Readability of code cannot be overestimated. And take a look at Why is “using namespace std;” considered bad practice?. Sooner or later it will create you problems.
You can create a vector of tuple to store the required data.
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
int main()
{ double voltage,rpm,current,range;
int total; //total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin>>total;
cout<<"\n";
std::vector<std::tuple<double, double, double, double>> data;
for(int i=1;i<=total;i++)
{
cout<<"Enter he voltage "<<i<<":";
cin>>voltage;
cout<<"Enter the current "<<i<<":";
cin>>current;
cout<<"Enter the rpm "<<i<<":";
cin>>rpm;
cout<<endl;
double range= (voltage*1.2) + (current*0.5) + (rpm* 0.2);
data.emplace_back(std::make_tuple(current, current, rpm, range));
}
cout<<"Voltage\t\tCurrent\t\tRPM\t\tRange\n";
for(const auto& tup : data)
cout<<std::get<0>(tup)<<"\t\t"<<std::get<1>(tup)<<"\t\t"<<std::get<2>(tup)<<"\t\t"<<std::get<3>(tup)<<endl;
return 0;
}

C++ program not able to open files from user input

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main() {
ifstream inputFile;
string fileName;
int value = 0;
int numOfNumbers = 0;
int oddNumbers = 0;
int evenNumbers = 0;
double sum = 0.0;
double average = 0.0;
int counter = 0;
//Ask user for file name
cout << "Enter file name to read: " << endl;
cin >> fileName;
//Open file
inputFile.open(fileName);
//Calculate information
if (inputFile.is_open())
{
while (inputFile >> value)
{
numOfNumbers++;
sum += value;
}
}
else
{
//Display error if file doesn't open
cout << "Error reading file." << endl;
}
if (numOfNumbers > 0)
average = sum / numOfNumbers;
else
average = 0.0;
if (numOfNumbers > 0)
{
while (inputFile >> value)
{
counter++;
if (value % 2 == 0)
evenNumbers++;
else
oddNumbers++;
}
cout << "Number of numbers = " << numOfNumbers << endl;
cout << "Average = " << average << endl;
cout << "Sum = " << sum << endl;
cout << "Number of even numbers: " << evenNumbers << endl;
cout << "Number of odd numbers: " << oddNumbers << endl;
}
else
cout << "Cannot compute values." << endl;
inputFile.close();
return 0;
}
I cannot get this program to open my file nor read the contents to do these calculations. I have moved the file into the directory and have tried typing the name with the extension (.txt). I also removed the quotations I previously had placed around fileName in inputFile.open(fileName);
Any recommendations?

overriden method first c++

I am reading a book about c++ programming and there is an exercice that should be solved with virtual:
//Main.cpp
#include "stdafx.h"
#include "Employee.h"
#include "Manager.h"
#include <vector>
#include <iostream>
#include <stdlib.h>
using namespace std;
//Generates the choice of which type of employee we are working on.
int generate_type_choice() {
cout << "1.Manager" << endl;
cout << "2.Enginner" << endl;
cout << "3.Researcher" << endl;
int choice=0;
cin >> choice;
return choice;
}
void addEmployee(vector<Employee*>* v) {
int choice = generate_type_choice();
cout << "first name: ";
string Fname;
cin.ignore();
getline(cin, Fname);
string Lname;
cout << "Last Name: ";
getline(cin, Lname);
cout << "Salary: ";
float s;
cin >> s;
switch (choice) {
case 1: {
cout << "Number of Meetings per week: ";
int m,vac;
cin >> m;
cout << "Number of vacation days per year: ";
cin >> vac;
Employee* e = new Manager(Fname, Lname, s, m, vac);
(*v).push_back(e);
break;
}
}
(*v).push_back(new Employee(Fname, Lname, s));
}
void printVector(vector<Employee*> v) {
for each (Employee* e in v)
{
(*e).printData();
}
}
int main()
{
vector<Employee*> v;
int choice = 0;
cout << "1.Add Employee" << endl;
cin >> choice;
switch (choice) {
case 1: {
addEmployee(&v);
}
}
printVector(v);
system("pause");
return 0;
}
//Employee.cpp
#include "stdafx.h"
#include "Employee.h"
#include <string>
#include <iostream>
using namespace std;
Employee::Employee()
{
Fname = "NoName";
Lname = "NoName";
salary = 0;
}
Employee::Employee(string f, string l, float s) {
Fname = f;
Lname = l;
salary = s;
}
void Employee::printData() {
cout << "First Name: " << Fname << endl;
cout << "Last Name: " << Lname << endl;
cout << "salary: " << salary << endl;
}
//Manage.cpp
#include "stdafx.h"
#include "Manager.h"
#include <string>
#include <iostream>
using namespace std;
Manager::Manager()
{
NumMeetings=0;
NumVacations=0;
}
void Manager::printData() {
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
}
what i want here is to call the employee::printData and after that call Manager::printData
...
(Employee is the parent Class of Manager)
i didn't put Getters and Setters to reduce the code and it is not a finished code so switch doesn't have only one case
You can use the :: to call the superclass' operator:
void Manager::printData() {
Employee::printData();
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
}
You can call the base function from the derived function.
void Manager::printData() {
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
Employee::printData();
}
Will print the Manager part and then Employee::printData(); will call printData just using the Employee part of the object to print out the rest.

C++ working with files, having trouble making a program

I am trying to make a simple program that can continously add data to a .txt document. Take a look at my code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream playersW("players.txt");
ifstream playersR("players.txt");
int id;
string name, info = "";
float money;
while (playersR >> id >> name >> money) {
if (playersR.is_open()) {
info += to_string(id) + " " + name + " " + to_string(money) + "\n";
}
}
playersW << info;
playersR.close();
cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;
while (cin >> id >> name >> money) {
if (playersW.is_open()) {
playersW << id << " " << name << " " << money << endl;
}
}
playersW.close();
}
What I want is the program to first read the data that is stored in players.txt and then write it again and also add the new additional data to players.txt.
EDIT: With the code I have now, my program only writes in the file players.txt the new information that the user enters.
this is a simple program that can open the file players.txt in binary mode so it first reads the content and displays it then it asks the user to input new players until the user enters 0 or negative player id so the loop breaks and then it closes the file to save the new appended content:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
fstream players("players.txt");
int id;
string name, info = "";
float money;
while (players >> id >> name >> money)
cout << name << " " << id << " " << money << endl;
players.clear();
players.seekp(0, ios::end);
cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;
while(1)
{
cout << "id: ";
cin >> id;
cout << endl;
if(!cin || id <= 0)
break;
cout << "name: ";
cin >> name;
if(!cin)
break;
cout << endl;
cout << "money: ";
cin >> money;
if(!cin)
break;
cout << endl;
players << id << " " << name << " " << money << endl;
}
players.close();
return 0;
}

Using user input to define array

I have a project where I need to create a shopping list with checkout functionality. I am trying to create an array using a users input. They supply how many products they are purchasing and I need to use that to define the size of the array.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct shopList {
double pluCode;
string product;
int saleType; // 0 = per unit, 1 = per pound
double price;
double inventory;
};
int main(){
char line[255];
const int items = 0;
int n;
ofstream outfile;
outfile.open("products.txt");
cout << "How many items in your checkout: ";
cin >> items;
shopList shop[items];
for (n = 0; n < items; n++) {
cout << "Enter the PLU code: ";
cin >> shop.pluCode;
outfile << shop.pluCode << " ";
cout << "Enter product name: ";
cin >> shop.product;
outfile << shop.product << " ";
cout << "Enter the price type (0 for per unit, 1 for per pound): ";
cin >> shop.saleType;
outfile << shop.saleType << " ";
cout << "Enter the price of the product: ";
cin >> shop.price;
outfile << shop.price << " ";
cout << "How much will you purchase: ";
cin >> shop.inventory;
outfile << shop.inventory << " " << "\n";
}
outfile.close();
ifstream infile;
infile.open("products.txt");
infile.getline(line, 255);
cout << line << endl;
}
It's possible , you just have to change your declaration like that;
int items = 0 ;
cin >> items;
shopList *shop = new shopList [items];