FORMATED AND UNFORMATTED INPUT AND OUTPUT

Formatted input and output of numerical values,for example,requires the >> and << operators and appropriate manipulators or formatting methods.

double price=12.34;
ofstream textfile(“Test.txt”);
textFile<<“Price:”<<price<<“Dollar”<<endl;
the file Test.txt will contain a line of text,such as “Price….” that exactly matches the screen output.
Transferring data block:
the ostream method write() transfer given number of bytes from main memory to a file.

WRITING OF FILE:

Example of writing to a file:

#include <iostream> 
#include <fstream> 
using namespace std; 
int main () { 
ofstream filestream("best.txt"); 
if (filestream.is_open()) 
{ 
filestream << "Welcome to C++ tutorial.\n"; 
filestream << "write to a file\n"; 
filestream.close(); 
} 
else cout <<"File opening is fail."; 
return 0; 
} 
 
Output:
The content of a text file best.txt is set with the data:
Welcome to C++ tutorial.
write to a file.

READING of a File:
1.Example of reading the file

#include <iostream> 
#include <fstream> 
using namespace std; 
int main () { 
string srg; 
ifstream filestream("test.txt"); 
if (filestream.is_open()) 
{ 
while ( getline (filestream,srg) ) 
{ 
cout << srg <<endl; 
} 
filestream.close(); 
} 
else { 
cout << "File opening is fail."<<endl; 
} 
return 0; 
} 
 
Note: "test.txt" is need to be created before running the program so that it can display the content written in the file:
Welcome to C++ tutorial.
write to a file.
Output:
Welcome to C++ tutorial.
write to a file.

Read and Write a file:

#include <fstream> 
#include <iostream> 
using namespace std; 
int main () { 
char input[75]; 
ofstream os; 
os.open("gig.txt"); 
cout <<"Writing to a text file:" << endl; 
cout << "Please Enter your name: "; 
cin.getline(input, 100); 
os << input << endl; 
cout << "Please Enter your age: "; 
cin >> input; 
cin.ignore(); 
os << input << endl; 
os.close(); 
ifstream is; 
string line; 
is.open("gig.txt"); 
cout << "Reading from a text file:" << endl; 
while (getline (is,line)) 
{ 
cout << line << endl; 
} 
is.close(); 
return 0; 
} 
 
Output:
Writing to a text file:  
 Please Enter your name:abhishek verma    
Please Enter your age: 18  


 Reading from a text file: abhishek verma  

Translate »