Write a program that Reads a file of unknown length You can

Write a program that:

Reads a file of unknown length. You can assume that each line in the file consists only of lowercase letters and spaces.

Outputs the shortest word in the file to the console.

Outputs the longest word in the file to the console.

Outputs the total number of words in the file to the console.

The file contains the following:


Your output should be:

Solution

// C++ code count words in file and find shortest and longest word

#include <iostream>
#include <string.h>
#include <fstream>
#include <limits.h>
#include <stdlib.h>
#include <math.h>
#include <iomanip>

using namespace std;

int main()
{
    ifstream inFile; //Declares a file stream object
    string fileName;
    string word;
    int count = 0;
    int maxlength = 0;
    string longword, shortword;
    int minlength = INT_MAX;

    cout << \"Enter the file name: \";
    getline(cin,fileName);

    inFile.open(fileName.c_str());

    while(true)
    {           
        inFile >> word;
        count++;

        if(word.size() < minlength)
          {
            shortword = word;
            minlength = word.size();

          }
        else if(word.size() > maxlength)
            {
                longword = word;
                maxlength = word.size();
            }
        if (inFile.eof())
        {
            break;
        }
    }
    inFile.close();

    cout << \"Shortest word: \" << shortword << endl;
    cout << \"Longest word: \" << longword << endl;
    cout << \"Number of words: \" << count << endl;

    return 0;
}

/*
output:

Enter the file name: input.txt
Shortest word: i
Longest word: orangutans
Number of words: 10


*/

Write a program that: Reads a file of unknown length. You can assume that each line in the file consists only of lowercase letters and spaces. Outputs the short
Write a program that: Reads a file of unknown length. You can assume that each line in the file consists only of lowercase letters and spaces. Outputs the short

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site