打开文件并输出功能
Opening a file and outputting for function
我有一个正在做的代码,我得到了基本版本的帮助,我需要有关如何实现一个函数的帮助,在该函数中,程序读取我保存的文本文件并读取它并根据函数输出它。这是我的代码和我到目前为止所拥有的..
#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;
}
相关文章:
- 不正确的比较和交换计数器输出用于快速排序功能
- C++:功能在输出前自动使用50减/增加输入数
- 下面的代码是如何工作的?它输出分解的数字并且功能齐全,我只是不明白它是如何做到的
- 打开文件并输出功能
- C 虚拟功能的输出
- 如何捕获C 功能printf()的输出
- C 尝试使用模板输出功能来显示不同类型的数据
- 为什么使用快速扫描功能时没有得到所需的输出?
- 将功能输出分配给变量
- Can std :: make_unique将功能的输出作为参数
- 无效指针功能的输出
- 相同的比较功能为C++中的排序和优先级队列提供不同的输出
- 我不确定为什么我会从功能中获得此输出
- 将数组传递到功能中,没有输出
- 如何将具有功能的日历程序输出到.txt文件
- 对于此简单功能,为什么编译器输出如此不同
- 使用嵌套功能时,Ostream输出会提供额外的地址
- 如何在大文件上高效地使用文件输入/输出功能(使用有限大小的内存)
- 输出功能C++出现故障
- C++打印输出功能