Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How to display results of files. C++ How to display results of a file I just wro

ID: 3695804 • Letter: H

Question

How to display results of files. C++

How to display results of a file I just wrote in this format

first.txt                                   your first name as written in the file

Here is what I have:


   string file; //This is a declaration for a file name
   string firstname; //This is a declaration for the first name file
   string lastname; //This declares the last name file
                   //The is a variable declaration for a first and last name
   string fname;
   string lname;

   ofstream myfile;

   cout << "Please enter the file name of your first name:";
   cin >> file;


   if (fileOpen(file, myfile, ios::out))
   {
       cout << endl << "Your file has successfully opened." << endl;
       cout << "Please enter your first name:"; //asks the user to input first name
       cin >> firstname; //user inputs first name
       myfile << firstname;
       myfile.close(); //closes the file
   }
   else
   {
       cout << "Error opening file" << endl;
   }

Explanation / Answer

#include<iostream>
#include<fstream>
#include<sstream>

using namespace std;

int main(){
  
   string file; //This is a declaration for a file name
string firstname; //This is a declaration for the first name file
string lastname; //This declares the last name file
//The is a variable declaration for a first and last name
string fname;
string lname;

ofstream myfile;

cout << "Please enter the file name of your first name:";
cin >> file;

   myfile.open(file.c_str());

if (!myfile.fail())
{
cout << endl << "Your file has successfully opened." << endl;
cout << "Please enter your first name:"; //asks the user to input first name
cin >> firstname; //user inputs first name
myfile << firstname;
myfile.close(); //closes the file
}
else
{
cout << "Error opening file" << endl;
}

// now reading from file
cout<<" Reading from file ";
ifstream read(file.c_str());
string first;
read>>first;
cout<<"First Name: "<<first<<endl;
read.close();
   return 0;
}

/*

Output:

Please enter the file name of your first name:first.txt

Your file has successfully opened.
Please enter your first name:Pravesh

Reading from file
First Name: Pravesh

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote