Reading An External Text File
Oct 15, 2018 at 7:19pm UTC
Hi guys. I'm having a really hard time reading a text file. My teacher gave us an assignment and the code I wrote below should use the text file she gave us to read the input file (the name is input.txt) but when I run the code nothing comes up. It just says "C:\Users\Ibrahim Abukwaik\source\repos\Project 2\Debug\Project 2.exe (process 19264) exited with code 0.
Press any key to close this window . . ."
How do I make my code run? The program is successful so I didn't think there were any errors in the code but maybe I'm wrong...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
ofstream fout;
double calCost(int quantity, double cost) {
double totalCost;
totalCost = quantity * cost;
return totalCost;
}
double acctotal(double totalCost, double itemCost) {
double newTotalCost;
newTotalCost = totalCost + itemCost;
return newTotalCost;
}
void writeLine(string itemno, int quantity, double unitCost, double totalCost) {
fout << left << setw(15) << itemno << left << setw(15) << quantity << left << setw(15) << unitCost << left << setw(15) << totalCost << endl;
}
void printHeader(string date) {
fout << "Invoice date:" << date << endl;
}
void printTotal(double invoiceTotal) {
fout << "Total................................................" << invoiceTotal << endl;
}
int main() {
fout.open("input.txt" );
ifstream fin;
fin.open("input.txt" );
if (fin.is_open()) {
while (!fin.eof())
{
int items;
string date;
double invoiceCost = 0;
while (fin >> items >> date)
{
fout << endl;
printHeader(date);
fout << left << setw(15) << "Item" << left << setw(15) << "Quantity" << left << setw(15) << "Unit Price" << left << setw(15) << "Total Price" << endl;
for (size_t i = 0; i < items; ++i)
{
string itemno;
int quantity;
double unitCost;
fin >> itemno >> quantity >> unitCost;
double totalCost;
totalCost = calCost(quantity, unitCost);
invoiceCost = acctotal(invoiceCost, totalCost);
writeLine(itemno, quantity, unitCost, totalCost);
}
printTotal(invoiceCost);
}
}
}
else {
cout << "Error in opening input file \n" ;
}
return 0;
}
Oct 16, 2018 at 6:22am UTC
Whether there are errors depends on what you want to achieve.
Note that fout
and fin
will use the same file "input.txt". I guess that you want "output.txt" for fout
?
I suggest that you make some debug cout << ...
just to see what happening while running the program.
Topic archived. No new replies allowed.