Write program to input a multi-word string from keyboard and write this input string along with first letter of each of its word into a file “initials.txt”. Data already present in the file initials.txt must be preseved. Display suitable error message if the file opening/writing operation fails.
#include <iostream>
#include <fstream>
#include <string.h>
#include <ctype.h>
using namespace std;
int main()
{
//variable declaration
string s;
int i=0;
//get user input
cout<<"Enter a string: ";
getline(cin, s);
//create object
fstream file;
//open file again
file.open("initials.txt", ios::app);
//check if file is opened successfully
if(file)
{
//append the content to the file
file<<s[0];
while(s[i]!='\0')
{
if(s[i]==' ')
file<<s[i+1];
i++;
}
}
else
{
cout<<"File not opened successfully!";
}
//close the file
file.close();
return 0;
}
INPUT:
Enter a string: Ok Do It
OUTPUT:
initials.txt
ODI
Comments
Leave a comment