我有一个家庭作业,我遇到了一些困难,因为老师正在分配我们甚至没有完全讨论过的作业。我对 infile/outfiles 有一些了解,但我在两个主要方面遇到了麻烦:
如何让 outfile 读取我的字母代码作为特定的收费金额,以及如何将第二行作为孩子继续到我的第一行。
注意,他不允许我们使用向量,而是希望我们使用简单的 C++ 工具。

我尝试使用 if 语句来检查字符,如果它匹配,则设置所述代码的费用并乘以该值。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// VARIABLES
ifstream infile; // Input file stream
ofstream outfile; // Output file stream
const double treeRemove = 300.00;
const double treeTrim = 50.00;
double treeStump = 20.00;
double discount = 0.90;
double treeStumpPlus = 2.00;
double chargeR = 300;
double chargeT = 50;
//double chargeG;
char letterCode;
int val = 0, recNum = 0, i = 0; // All ints declared
double total = 0; // Totals as a double (incase of decimal)
// Open infile, if issues show error
infile.open("C:\\temp\\infile.txt");
if (!infile.is_open()) {
cout << "Could not open file: 'infile.txt'" << endl;
system("pause");
return 1; // Error return
}
// Open outfile
outfile.open("C:\\temp\\outfile.txt");
// Header
outfile << "Orlando Tree Service Totals" << endl << endl;
// Prime
infile >> letterCode >> val;
// Start out infile check and while loop.. Clear up the int values
while (infile) {
val = 0;
chargeR = 0;
chargeT = 0;
total = 0;
for (i = 0; i < 4; ++i) {
if (letterCode == 'R') {
chargeR = val * treeRemove;
}
if (letterCode == 'T') {
chargeT = val * treeTrim;
}
total = chargeR + chargeT;
infile >> letterCode >> val;
}
++recNum; // Increase record num by 1
// Write to file
outfile << "Record #" << recNum << "... Tree Removal: " << chargeR << " Tree Trim " << chargeT << " Total: " << total << endl;
}
// Done with file, so close it
outfile.close();
infile.close();
cout << "Done! Please check the output file to verify..." << endl;
system("pause");
return 0;
}
当前输入文件:
R 7 T 6.5
R 0 T 2.0
R 3 T 0
R 1 T 0
R 0 T 0
R 2 T 7.5
当前输出文件:
Orlando Tree Service Totals
Record #1... Tree Removal: 0 Tree Trim 300 Total: 300
Record #2... Tree Removal: 900 Tree Trim 0 Total: 900
Record #3... Tree Removal: 0 Tree Trim 0 Total: 0
Record #4... Tree Removal: 0 Tree Trim 350 Total: 350
如您所见,结果没有正确生成,我认为这与我的 for 语句有关,但我没有发现问题?
编辑:我展示了我的其余代码只是为了澄清
编辑:使用括号修复更新代码以使 outfile 活跃起来。