打开文件并输出功能

Opening a file and outputting for function

本文关键字:输出 功能 文件      更新时间:2023-10-16

我有一个正在做的代码,我得到了基本版本的帮助,我需要有关如何实现一个函数的帮助,在该函数中,程序读取我保存的文本文件并读取它并根据函数输出它。这是我的代码和我到目前为止所拥有的..

#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

这是一种方法,假设您的数据由空格或新行拆分:

#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;
}

你像这样使用它:

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;
}