Create a plain text file with the following contents this fi
Create a plain text file with the following contents:
“this file contains only lowercase letters”
Write a C++ program that does the following:
Opens the text file and reads in the text.
Displays the text to the screen.
Converts the text to all capital letters and displays that to the screen.
Hint: take advantage of the ASCII character code to convert the letters from lowercase to uppercase. (Program Used: Visual Studio, C++)
Solution
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile; // For input file
char ch,ch2;
string myOutput;
// Open input file
inFile.open(\"file.txt\");
if (!inFile)
{
cout << \"Cannot open file\" << endl;
return 0;
}
cout<<\"File contents\"<<endl;
while (inFile.get(ch))
{
cout<<ch;
}
// Read characters from input file
cout<<\"\ capitalizing file contents\"<<endl;
inFile.clear(); //clearing eof flag that has been set by reading
inFile.seekg(0, ios::beg); //move file pointer to beginning
while (inFile.get(ch))
{
//ch2 = toupper(ch);
if(isalpha(ch))
{
ch2 = ch-32; //use ascii code eg a = 97 , 97-32 = 65 which is ascii code of A
cout<<ch2;
}
}
// Close file
inFile.close();
return 0;
}
file.txt
“this file contains only lowercase letters”
output:
File contents “this file contains only lowercase letters”
capitalizing file contents
“THISFILECONTAINSONLYLOWERCASELETTERS”

