Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Text files What we want to do is to test our ability to write to a text file and later read from it. Suppose we
Text files
- What we want to do is to test our ability to write to a text file and later read from it. Suppose we wrote a program like the following:
(just the main body)
int n1 = 3;
int n2 = 10;
ofstream outFile;
outFile.open(test.txt);
outFile << n1 << endl;
outFile << n2 << endl;
outFile.close();
ifstream inFile;
inFile.open (test.txt);
inFile >> n1;
inFile >> n2;
inFile.close();
cout << n1: << n1 << endl;
cout << n2: << n2 << endl;
If you ran this and it printed out 3 for n1 and 10 for n2, is this proof that your program correctly wrote to a text file and then read from it? If you think so, try copying it and running it.
- After it runs, try modifying the second file name test.txt to abc.txt and see how it runs. Whats going on?
- Add test.txt to resource files in your project. Where was the file located? If you were going to add a file to a project for reading data, what directory would you put that file in? Did you find abc.txt in this directory?
- Change the type of the variable to be an integer and a float. Initialize these variables to interesting values such as 12345 and 88.9922. Rerun the program after making any modifications to get it to run.
- Reverse the order of reading the values from the file. What is the result and why?
- Take away lessons:
- The direction that a file should be located so that it can be opened and read is: _______________________
- File open should be tested every time a file is opened so that we will not assume that a file is open when it is not. If a file is not correctly opened, we want to receive a message indicating this.
- The order in which data is extracted from a file is critical to it being accurately extracted.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started