180k views
1 vote
Write a program that asks the user for two file names. The first file will be opened for input and the second file will be opened for output. (It will be assumed that the first file contains sentences that end with a period.) The program will read the contents of the first file and change all the letters to lowercase except the first letter of each sentence, which should be made uppercase. The revised contents should be stored in the second file.

User Abinash
by
4.5k points

1 Answer

2 votes

Answer:

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

//First we declare string variables to store file names for input and output

string inputName;

string outputName;

string sentence;

// Then declare char variable to get current char

char ch;

//The following section will prompt theuser to enter the file names and read

cout << "Enter input file name:\\";

cin >> inputName;

cout << "Enter output file name:\\";

cin >> outputName;

//ignore newline character left inside keyboard buffer

cin.ignore();

//Next we define the input and output files to be opened

ifstream inputFile(inputName);

ofstream outputFile(outputName);

if(!inputFile && !outputFile){

cout << "Error while opening the files!\\";

cout << "Please try again!\\";

//end program immediately

return 0;

}

//Using this loop to get lines one by one, delimited by '.'

while(getline(inputFile, sentence, '.')){

//bool variable to store if we have already

//printed capital first letter

bool alreadyCapitalized = false;

//Using of for loop on all characters of sentence

for(int counter = 0; counter < sentence.length(); counter++){

//if not alphabetical character,

//so whitespace or newline, print as is

if(!isalpha(sentence[counter]))

outputFile << sentence[counter];

//Condition statement for if it is alphabetical and no capitalization has been done, print it as uppercase

if(!alreadyCapitalized && isalpha(sentence[counter])){

outputFile << (char)toupper(sentence[counter]);

alreadyCapitalized = true;

}

//otherwise print this condition as lowercase

else if(alreadyCapitalized)

outputFile << (char)tolower(sentence[counter]);

}

//Printing of the output sentence with period in the end

outputFile << ".";

}

//Closing the files

inputFile.close();

outputFile.close();

return 0;

}

User Nayuki
by
4.8k points