0

Write a C++ program that prompts the user for a filename. It should try to open the provided file. If it is invalid, continue looping and prompting until a valid file is opened. The program should read all of the tweets from the file (until EOF), then output the following analysis:

Number of hashtags.
Number of Twitter ID's
Total number of tweets
Length of the longest tweet
Length of the shortest tweet
Average length of all tweets (with 2 digits past the decimal point precision)

Up above is the assignment for me to do, and I am really confused on how I should approach this problem. So far this is the code that I have written, any steps to the right direction?

#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;

int main() {

    ifstream inputFile;
    string filename;
    string string;
    int count = 0;
    char hashtag;

    cout << "Filename to open?" << endl;
    cin >> filename;

    inputFile.open(filename);



    if (inputFile.good()){

        cout << "Analysis for file tweets.txt: " << endl;


       inputFile.close();
   }

        else
        {

            cout << "Error opening the file." << endl;
        }
    while (!inputFile.eof()){

        inputFile >> hashtag;

        if (hashtag == '#')

        count ++;

    }



    cout << count << " Number of hashtags" << endl;

    return 0;
}
daoz1
  • 43
  • 5
  • What exactly are you confused about? For tasks dealing with text files, you want to stream the file into a character buffer (don't forget to close the stream), and create a string object from it, which allows you to perform arbitrary operations, such as splitting the string into multiple strings, counting character/word occurrences, etc. [string tutorial](https://www.geeksforgeeks.org/stdstring-class-in-c/) – tonayy Oct 06 '19 at 08:46
  • 1
    You should read questions like [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Shawn Oct 06 '19 at 08:47

0 Answers0