C++ Language



Admission Enquiry Form

  

Write and Read String into the File using different ways:


Code to write a string into the file using fstream class in ios::out mode.

//Write a string into the file
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
// create a file and open it write mode
fstream finout("c:\\compuhelp\\string.txt",ios::out);
finout<<"Welcome to Compuhelp";
cout<<"Data saved ";
finout.close();
}




Code to read a string from the file using fstream class in ios::in mode.

//Read a string from the file
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char name[100];
// open the file in read mode
fstream finout("c:\\compuhelp\\string.txt",ios::in);
finout>>name;
cout<<name;
finout.close();
}


Note:

The above code will read the string but only before space.The string after space will not be read by the compiler.If we have to read the whole string using spaces then we use getline() function.


Code to read a string from the file using getline() function.

//Read a string using getline() function
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char name[100];
ifstream fin("c:\\compuhelp\\string.txt");
fin.getline(name,30);
cout<<name;
fin.close();
}

Note:

The above code will read the string with spaces from the file due to getline() function.