File I/O

I am trying to write a program for class that reads from an input file the month, year & total collected. I am using notepad for the input file.

This is what the notepad file looks like
-----------------------------------
March 2013 63924.62


Why does it give me random numbers in the output rather than what the notepad has?

Also, the outfile is completely blank.

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
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main ()
{
	ifstream infile;
	char month;
	int year;
	double total_collected;

	ofstream outfile;

	const double CITY_TAX_RATE  = .02,
		     STATE_TAX_RATE = .04,
		     SALES_CUTOFF   = 100000,
		     TAX_BREAK      = .10;

	cout << "The march tax report has been saved to prog3_252out.txt" << endl
		 << year << "---" << total_collected << "---" << month << endl;

	infile.open("prog3_252inp.txt");

	if(!infile)
	infile >> month;
	infile >> year;
	infile >> total_collected;

	infile.close();

	outfile.open("prog3_252out.txt");

	if(!outfile)
	outfile << "Name" << endl
			<< "Class" << endl
			<< "Date" << endl
			<< endl
			<< endl
			<< "Month:" << setw(14) << month << "," << year << endl
			<< "----------------------------------" << endl
			<< "Total Collected:" << endl
			<< "Sales:" << endl
			<< "City Sales Tax:" << endl
			<< "State Sales Tax:" << endl
			<< "Total Sales Tax:" << endl
			<< "----------------------------------" << endl;

	outfile.close();

	return 0;
}


OUTPUT
--------------

The march tax report has beens saved to prog3_252out.txt
1629962336---1.02118e+160---a
char month;

You've allocated exactly one char to hold the month value. You need... more - std::string would be appropriate.

After you extract one char from the input file ('M') you try to extract numbers into year and total_collected. However, the input stream looks like: "arch 2013 63924.62" and as you can't stuff "arch" into an int, the input stream is put into an error state which is never cleared (or tested for.)

[Edit: Scratch that. You don't even attempt to extract the month if the file was succesfully opened. You only do so when the file was not. (line 26 is paired with line27.)]
Last edited on
1. Line 26: infile >> month; is only accessed if infile is false. It should be the other way around. Also you may want the input of year and total_collected to also depend on the boolean value for infile.

2. You've made month a char variable so that the code snippet infile >> month; will only store the single character 'M'. To solve this add the directive #include <string> and do string month
Topic archived. No new replies allowed.