67 128
Assignments Done
99,3%
Successfully Done
In November 2018

Answer to Question #69474 in C++ for Jcullen

Question #69474
3. Write a C++ program to open and read text from a text file character by character. The text file named “test.txt” contains following text:
Hello friends, How are you?
I hope you are fine and learning well.
Thanks and good bye!

The program will read text from the file character by character and display it on the output screen.
Use the following design logic to write the program:

1. Open file in read/input mode using std::in
2. Check file exists or not, if it does not exist terminate the program
3. If file exist, run a loop until EOF (end of file) not found
4. Read a single character using cin in a temporary variable
5. And print it on the output screen
6. Close the file
Expert's answer
Answer:
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char* argv[]) {
// Open file in read/input mode using std::in
ifstream testfile("test.txt", ios_base::in);

// Check file exists or not, if it does not exist terminate the program
if (testfile.good()) {
// If file exist, run a loop until EOF (end of file) not found
while (!testfile.eof()) {
char temp;
// Read a single character using cin in a temporary variable
testfile.read(&temp, 1);

// And print it on the output screen
cout << temp;
}
// Close the file
testfile.close();
}

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions