Retrieve program r andomAccess.cpp and the data file proverb.txt Exercise 1: Fil
ID: 3633057 • Letter: R
Question
Retrieve program randomAccess.cpp and the data file proverb.txt
Exercise 1: Fill in the code as indicated by the comments in bold. Proverb.txt contains the following information:
Now Is The Time fOr All GoOd Men to come to the aid of their Family
Sample Run:
The read position is currently at byte 0
Enter an offset from the current position: 4
The character read is I
If you would like to input another offset enter a Y y
The read position is currently at byte 5
Enter an offset from the current position: 2
The character read is T
If you would like to input another offset enter a Y y
The read position is currently at byte 8
Enter an offset from the current position: 6
The character read is e
If you would like to input another offset enter a Y y
The read position is currently at byte 15
Enter an offset from the current position: 44
The character read is r
If you would like to input another offset enter a Y y
The read position is currently at byte 60
Enter an offset from the current position: 8
The character read is r
If you would like to input another offset enter a Y n
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
fstream inFile("proverb.txt", ios::in);
long offset;
char ch;
char more;
do
{
// Fill in the code to write to the screen
// the current read position (with label)
cout << "Enter an offset from the current read position: ";
cin >> offset;
// Fill in the code to move the read position "offset" bytes
// from the current read position.
// Fill in the code to get one byte of information from the file
// and place it in the variable "ch".
cout << "The character read is " << ch << endl;
cout << "If you would like to input another offset enter a Y"
<< endl;
cin >> more;
// Fill in the code to clear the eof flag.
} while (toupper(more) == 'Y');
inFile.close();
return 0;
}
Explanation / Answer
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
fstream inFile("c:\proverb.txt", ios::in);
long offset;
char ch;
char more;
int currPosition = 0;
do
{
cout<< "The read position is currently at byte "<<currPosition<<endl;
cout << "Enter an offset from the current read position: ";
cin >> offset;
currPosition = currPosition + offset + 1;
inFile.seekg(offset, ios::cur);
inFile.get(ch);
cout << "The character read is " << ch << endl;
cout << "If you would like to input another offset enter a Y"<< endl;
cin >> more;
if(inFile.eof())
{
inFile.seekg(0, ios::beg);
currPosition = 0;
}
} while (toupper(more) == 'Y');
inFile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.