In: Computer Science
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Please find below the code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you need any change in code. Else please upvote
CODE:
#include <iostream>
#include <fstream>
using namespace std;
//main function
int main()
{
ifstream infile; //input file stream object
string line; //variable to store each line in file
string firstWord; //variable to store the first word in each line
infile.open("document.txt", ios::in); //Open the file document.txt in read mode
if(!infile) { //checking if file exists
cout<<"File does not exist\n"; //display error if file not exists
return 1;
}
if(infile.peek() == EOF) { //checking if file is empty
cout<<"File is empty\n"; //display error if file is empty
return 1;
}
while (getline(infile, line)) //loop until last line in file
{
firstWord = line.substr(0, line.find(" ")); //Extract first word in the line
if(isupper(firstWord[0])) //if first character in firstWord is uppercase
cout << firstWord << endl; //print the firstWord
}
infile.close(); //closing the input file
return 0;
}
INPUT FILE (document.txt)
OUTPUT: