Example
#include<iostream.h>
#include<fstream.h> // in/out to file
main()
{
ofstream out("test");
// this part to confirm that the file was opened.
if(!out){
cout <<"Cannot open file";
return 1;
}
out << 10 << " "<<123.34<< "n";
out <<"This is a short text file";
out.close();
return 0;
}
The following program reads an integer, a float, a character and a string from the
file created by the previous program
Example
#include<iostream.h>
#include<fstream.h> // in/out to file
main()
{
char ch;
int i;
float f;
char str[80];
ifstream in("test");
if(!in){
cout << "Cannot open file";
return 1;
}
in >> i;
in >> f;
in >>ch;
in >>str;
cout << i<<" "<< f << " "<< ch << "n";
cout << str;
in.close();
return 0;
}
Keep in mind that when the >> operator is used for reading text files, certain character translations occur. For example whitespace characters are omitted. If you want to prevent any character translation you must open a file for binary access. Also when >> is used for a string input stops when the first white space character is encountered. To solve the string reading problem when spaces are encountered in the string you can use getline() function. One good use for the getline() to read strings that contains spaces.
For the string apply the following function
in.getline(str, 79); instead of in >>str;
Then the program should be
modified as
Example
#include<iostream.h>
#include<fstream.h> // in/out to file
main()
{
char ch;
int i;
float f;
char str[80];
ifstream in("test");
if(!in){
cout << "Cannot open file";
return 1;
}
in >> i;
in >> f;
in >>ch;
in.getline(str, 79);
cout << i<<" "<< f << " "<< ch << "n";
cout << str;
in.close();
return 0;
}
Another example on the getline() use is as follows:
Example
// use getline () to read a string that contains spaces
#include<iostream.h>
#include<fstream.h>
main()
{
char str[80];
cout << "Enter your name:";
cin.getline(str, 79);
cout <<str <<'n';
return 0;
}