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
1
Expert's answer
2017-08-08T06:50:41-0400
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(); }
Comments
Leave a comment