File input/output

Alright this is just a book exercise for my class and I can't figure out if I did this right or whats suppose to happen when doing file input output. I created a text file with the name inFile.txt and I input what it ask exactly how it is formatted. Am I suppose to create an output file too to be wrote too or is it suppose to create it itself? Below is the book instructions :

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
 Consider the following incomplete C++ program:

	#include <iostream>

	int main()
	{
		...
	}

		A) Write a statement that includes the header files fstream, string, and 
		   iomanip in this program.

		B) Write statements that declare inFile to be an ifstream variable and
		   outFile to be an ofstream variable.

		C) The program will read data from the file inData.txt and write output 
		   to the file outData.txt. Write statements to open both of these files, 
		   associate inFile with inData.txt, and associate outFile with outData.txt.

		D) Suppose that the file inData.txt contains the following data:

				Giselle Robinson Accounting
				5600 5 30
				450 9
				75 1.5

			The first line contains a person's first name, last name, and the department 
			the person works in. In the second line, the first number represents the monthly
			gross salary, the bonus (as a percent), and the taxes (as a percent). The third
			line contains the distance traveled and the traveling time. The fourth line
			contains the number of coffee cups sold and the cost of each coffee cup. Write
			statements so that after the program executes, the contents of the file outData.txt
			are shown as below. If necessary, declare additional variables. Your statements 
			should be general enough so that if the contents of the input file changes and the 
			program is run again (without editing and recompilin), it outputs the appropriate results.

				Name : Giselle Robinson, Department : Accounting
				Monthly Gross Salary: $5600.00, Monthly Bonus: 5.00%, Taxes: 30.00%
				Paycheck: $4116.00

				Distance Traveled: 450.00 miles, Traveling Time: 9.00 hours
				Average Speed: 50.00 miles per hour

				Number of Coffee Cups Sold: 75, Cost: $1.50 per cup
				Sales Amount = $112.50

		E) Write statements that close the input and output files.

		F) Write C++ program that tests the statements in parts a through e. 


And now here is what I have :

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

using namespace std;

int main()
{
	ifstream inFile;
	ofstream outFile;

	inFile.open("inData.txt");
	outFile.open("outData.txt");

	string firstName,
		lastName,
		department;

	double monthlySalary,
		monthlyBonus,
		taxes,
		distanceTraveled,
		travelingTime,
		coffeeCost,
		coffeeSales,
		payCheck,
		averageSpeed;

	int cupsSold;

	outFile << fixed << showpoint << setprecision(2);

	inFile >> firstName >> lastName >> department;
	outFile << "Name : " << firstName + ' ' + lastName << ", Department : " << department << endl;

	inFile >> monthlySalary >> monthlyBonus >> taxes;
	outFile << "Monthly Gross Salary : $ " << monthlySalary << ", Monthly Bonus : " << monthlyBonus << "%, Taxes : " <<
		taxes << "%" << endl;
	
	payCheck = ((monthlySalary) * (monthlyBonus/100)) * (taxes/100);

	outFile << "Paycheck : $" << payCheck << endl;

	inFile >> distanceTraveled >> travelingTime;

	averageSpeed = distanceTraveled / travelingTime;

	outFile << "Average Speed : " << averageSpeed << " mph" << endl;

	inFile >> cupsSold >> coffeeCost;

	coffeeSales = cupsSold * coffeeCost;

	outFile << "Sales Amount : $" << coffeeSales << endl;

	inFile.close();
	outFile.close();

	cin.get();

	return 0;
}
Your sample input file should look something like:
1
2
3
4
Giselle Robinson Accounting
5600 5 30
450 9
75 1.5

You'll use this input file to determine if you're reading the file correctly.

After your program executes your output file should look something like what's shown in your text.

I will say that you have appeared to have completed A, B, C the way the book suggests but IMO B and C should be:
1
2
3
	ifstream inFile("inData.txt");
	ofstream outFile("outData.txt");


You should prefer to use the constructors to open the files whenever possible. Also step E is really not required. The class destructors will close the files automatically when the stream goes out of scope (then end of the program).

I would recommend that you first read the input file, then write the output file, instead of interleaving the read and write operations.
I do have a input text file like :
1
2
3
4
Giselle Robinson Accounting
5600 5 30
450 9
75 1.5


I will rewrite it so that it reads all the input first them the output too, make it more readable.

So when it executes, nothing will show on the console screen correct? The output should be in the text file outData.txt right? This output

1
2
3
4
5
6
7
8
9
Name : Giselle Robinson, Department : Accounting
Monthly Gross Salary: $5600.00, Monthly Bonus: 5.00%, Taxes: 30.00%
Paycheck: $4116.00

Distance Traveled: 450.00 miles, Traveling Time: 9.00 hours
Average Speed: 50.00 miles per hour

Number of Coffee Cups Sold: 75, Cost: $1.50 per cup
Sales Amount = $112.50
Last edited on
When I debug this, step by step, none of the variables are getting initialized to whats in the sample input file.

Why would this be?
First are you sure the input file opened correctly? You need to check to insure it is properly opening.
no i is not properly opening, I implemented

1
2
3
4
5
6
7
8
if (inFile.is_open())
	{
		cout << "File opened" << endl;
	}
	else
	{
		return 1;
	}


and it debugs to else

So I'm comfused on where it is going wrong?

When I debug, the variables inFile and outFile both have this error code

{_Filebuffer={_Set_eback=0xcccccccc <Error reading characters of string.> _Set_egptr=0xcccccccc <Error reading characters of string.> ...} } std::basic_ifstream<char,std::char_traits<char> >
Last edited on
Trying to show inFile and outFile as variables probably won't work since they are classes.

But there are a couple of things you can do to see why the file failed to open. One it to have the program tell you a little more information as to why the file failed to open by using perror()

1
2
3
4
5
6
7
8
#include <cstdio>
...
else
{
   perror("File failed to open");
   return 1;
}
...


Remember that by default the file must exist when using an ifstream. So the usual failure is that there is no file with the proper name in the location your program is expecting it. Since you didn't provide any path information in the open command the file must be in the programs current working directory. The current directory can be in different places depending on how you are running the program. Various IDEs set the programs working directory to different locations so if you're using an IDE you'll need to read the documentation to determine the working directory location. Or since an ofstream will create a file if one doesn't exit you can use this fact to locate the working directory by trying to create an output file with an unique name that you can find with your operating systems find functionality.

yup the output says no such file exist or directory so I should put a path in where the ifstream inFile("Path"); is?
okay this is how I have the file directory set up

1
2
3
4
5
ifstream inFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
ofstream outFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");

inFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
outFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");


It still says there is still no directory and that is the exact directory from where the files are

I made a new text file and deleted the old one and for whatever reason now it opens but still produces extraneous results
Last edited on
And those extraneous results are? Please show exactly what output your program is producing.

output is :

1
2
3
4
5
Name :  , Department :
Monthly Gross Salary : $ -9.25596e+061, Monthly Bonus : -9.25596e+061%, Taxes : -9.25596e+061%
Paycheck : $ -7.92985e+181
Average Speed : 1 mph
Sales Amount : $7.95081e+070


so When I debug it, it is opening the file but it is not inputting the information that is in the file. Since there is no input it gives the string values nothing and the numeric variables random numbers. I don't understand why the information from the txt file is not being inputted into the variables
Last edited on
Please post your current code.

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdio>

using namespace std;

int main()
{	
	ifstream inFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
	ofstream outFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");

	inFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
	outFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");

	if (inFile.is_open())
	{
		cout << "File opened\n" << endl;
	}
	else
	{
		perror("File Failed to open");
		return 1;
	}

	string firstName,
		lastName,
		department;

	double monthlySalary,
		monthlyBonus,
		taxes,
		distanceTraveled,
		travelingTime,
		coffeeCost,
		coffeeSales,
		payCheck,
		averageSpeed;

	int cupsSold;

	//Set decimal value to .00

	outFile << fixed << showpoint << setprecision(2);

	//File Input

	inFile >> firstName >> lastName >> department;
	inFile >> monthlySalary >> monthlyBonus >> taxes;
	inFile >> distanceTraveled >> travelingTime;
	inFile >> cupsSold >> coffeeCost;

	//Calculate

	payCheck = ((monthlySalary) * (monthlyBonus/100)) * (taxes/100);
	averageSpeed = distanceTraveled / travelingTime;
	coffeeSales = cupsSold * coffeeCost;
	
	//Output to file
	
	outFile << "Name : " << firstName + ' ' + lastName << ", Department : " << department << endl;
	outFile << "Monthly Gross Salary : $ " << monthlySalary << ", Monthly Bonus : " << monthlyBonus << "%, Taxes : " <<
		taxes << "%" << endl;
	outFile << "Paycheck : $" << payCheck << endl;
	outFile << "Average Speed : " << averageSpeed << " mph" << endl;
	outFile << "Sales Amount : $" << coffeeSales << endl;

	//close files

	inFile.close();
	outFile.close();

	cout << "Name : " << firstName + ' ' + lastName << ", Department : " << department << endl;
	cout << "Monthly Gross Salary : $ " << monthlySalary << ", Monthly Bonus : " << monthlyBonus << "%, Taxes : " <<
		taxes << "%" << endl;
	cout << "Paycheck : $" << payCheck << endl;
	cout << "Average Speed : " << averageSpeed << " mph" << endl;
	cout << "Sales Amount : $" << coffeeSales << endl;

	cin.get();

	return 0;
}
When I run your program I get the following output:

1
2
3
4
5
Name : Giselle Robinson, Department : Accounting
Monthly Gross Salary : $ 5600.00, Monthly Bonus : 5.00%, Taxes : 30.00%
Paycheck : $84.00
Average Speed : 50.00 mph
Sales Amount : $112.50


Are you sure your input file only contains the following:
1
2
3
4
Giselle Robinson Accounting
5600 5 30
450 9
75 1.5


It looks like perhaps it is an empty file.
hmm, yes it does only contain that above input. The problem must be with my path or file. I'll play around with it some more. When I save the txt file does it need to have a different encoding? Not the ANSI one?
I'll just have to ask my professor, I tried everything I could think of and still nothing has worked.

I did create a txt file in notepad and called it "inFile" with the following input :

1
2
3
4
Giselle Robinson Accounting
5600 5 30
450 9
75 1.5


when I debug it, when it gets to the ifstream inFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt"); it produces the error :

 
inFile	{_Filebuffer={_Set_eback=0xcccccccc <Error reading characters of string.> _Set_egptr=0xcccccccc <Error reading characters of string.> ...} }	std::basic_ifstream<char,std::char_traits<char> >


when I get to the string variables I get the following error :

 
firstName	<Error reading characters of string.>	std::basic_string<char,std::char_traits<char>,std::allocator<char> >

What compiler are you using?

Please go to the command line, and change directory to where your file is located and first insure that there is a file with the name inFile.txt and if present note the size of this file. Also see if there is a file with the name of inFile.txt.txt note the two extensions, and if present note the size of this file as well. Then please post the results.



I am using Visual Studio Professional 2012

I ensured that the file does exist in E:\School\CIS276\C++ Book Exercises\Chapter 3\CH3-1\Text File and it is in there. The file is 53 bytes.

I do not have any file that is named inFile.txt.txt
I figured out the problem, the problem was this section of the code :

1
2
3
4
5
ifstream inFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
	ofstream outFile("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");

	inFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\inFile.txt");
	outFile.open("E:\\School\\CIS276\\C++ Book Exercises\\Chapter 3\\CH3-1\\Text File\\outFile.txt");


I took out the inFile.open statment and boom it worked. That statement somehow through off the compiler when assigning values.

any idea why? how does it open the files if I'm not opening them?
Last edited on
There are two ways of opening the files when dealing with C++ streams the constructor, the preferred way, and the open() function. Perhaps you should study the documentation for this standard class.

http://www.cplusplus.com/reference/fstream/ofstream/ofstream/
Topic archived. No new replies allowed.