Create a C++ program that will read a series of titles from an input file (Do no
ID: 3762582 • Letter: C
Question
Create a C++ program that will read a series of titles from an input file (Do not use fstream), one per line. The titles will be in an unorthodox mix of upper and lowercase letters. Reformat each title so that the first letter of each word is capitalized and all remaining letters are lowercase. For example, "thE CAT in tHe hat" becomes "The Cat In The Hat". Assume there are no leading spaces before the first word of each title and that each word is separated by 1 blank space. At least one function (in addition to main) must be used.
Here's a start:
#include <iostream>
#include <string>
Explanation / Answer
/**C++ program that open a input file input.txt
that contains the titles ,
Then read line by line and converts the titles to capitalize
the first letters and write to the file input.txt again.
*/
//files.cpp
//include header files
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//function prototype
//method to capitalize
string capitalize(string str);
int main()
{
//Create fstream object
//Note :without using file stream , files cannot be handled
fstream fin;
//open an input.txt
fin.open("input.txt");
//open a temp file in output mode
ofstream fout;
fout.open("temp.txt");
if(!fin)
{
cout<<"File doesot exist."<<endl;
system("pause");
}
string line;
//read file line
while( getline(fin, line) )
{
//call capitalize metod to set first letter capital
line=capitalize(line);
//write to temp file
fout<<line<<endl;
}
//close the input and temp files streams
fin.close();
fout.close();
//delete input.txt
remove("input.txt");
//rename temp to input.txt
rename("temp.txt","input.txt");
//remove temp.txt since no longer required.
remove("temp.txt");
//pause the program output on console
system("pause");
return 0;
}
/**Method capitallize that takes str as input argument
and capitalize the first letter and return the string*/
string capitalize(string str)
{
//set first letter capital
str[0]=toupper(str[0]);
for( int i=1;i<str.length();i++)
{
//if character at i is not space then set to lower case
if(str[i]!=' ')
str[i]=tolower(str[i]);
else
{
//if character is space then set next letter capital
str[i+1]=toupper(str[i+1]);
//increment the i by one
i++;
}
}
//returns str
return str;
}
--------------------------------------------------------------------------------------
Sample input.txt file
thE CAT in tHe hat
--------------------------------------------------------------------------------------------
sample output text file (converted during the program)
input.txt
The Cat In The Hat