Answer to Question #181190 in C++ for Kanav Garg

Question #181190

Write a program that asks the user to enter a filename followed by a command. If the user enters the command “print”, your program should print the contents of the file to the console exactly as it appears in the file. If the user enters the command “double”, your program should read each number contained in the file and print the number doubled to a separate line on the console.

 

1
Expert's answer
2021-04-14T07:06:50-0400
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("testing.txt",ios::out);
   if(newfile.is_open())
   {
      newfile<<"Testing of print statement \n";
      newfile.close();
   }
   newfile.open("testing.txt",ios::in); //open a file to perform read operation using file object
   if (newfile.is_open()){   //checking whether the file is open
      string tp,command;
      cout<<"Please enter the command: print or double"<<endl;
      cin>>command;
      if(command=="print"){

        while(getline(newfile, tp)){  //read data from file object and put it into string.
        cout << tp << "\n";   //print the data of the string
      }
      newfile.close();   //close the file object.
      }else{
      cout<<"test doble."<<endl;
      }

   }
}

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 the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS