Pages

Tuesday, October 18, 2011

Writing a string using put()

Using the put() to write a string

To write multiple characters in a file using the "put()", we can use the function inside a loop.  Without a loop it is not possible to write a complete string with put(), since the put() can not write more than one character at a time,

#include "conio.h"
#include "iostream.h"
#include "fstream.h"
#include "string.h"
void main()
{
 clrscr();
 ofstream of("file1.txt");
 char str[20];
 cout<<"\nEnter a string  : ";
 cin>>str;
 for(int i=0;i <strlen(str);i++)
of.put(str[i]);

cout<<"Saved";
 of.close();
}


The above program will ask the user to write a string that will be saved in the variable "str[]". A "for" loop has been used to write all the characters of the array from 0 to the length of the string. Inside the loop we have used the statement "of.put(str[i])", that will write the value of all the characters of the array in the file one char at a time. For using the "strlen()" we have used the header file "string.h".

Output
Enter a string : Programming
Saved

To view the file you can use the same process as described in the previous post.

0 comments:

Post a Comment