我有一个我正在做的代码,我得到了基本版本的工作,我需要帮助来解决如何实现一个函数,其中程序读取我保存的文本文件并读取它并根据它输出功能。这是我的代码和我到目前为止所拥有的......
#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
答案 0 :(得分:0)
这是一种方法,假设您的数据被空格或新行分割:
HeterogeneousContainer
你可以这样使用它:
#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;
}