Accessing a Text File in a Directory

I'm really lost on this one simply because my professor has only addressed accessing this within the code, not asking the user to select the text file to access.

The biggest issue I'm having currently is having the program ask the user for a text file name and, following this, the program should open the text and read how many lines, words, and characters are in the text file to the user. The program would then close the file and ask the user for another file to access.

This is my code currently.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

main()
{
        string word, line;
        int chars = 0, words = 0, lines = 0;

        ifstream in;

        in.open(" ");
        if (!in.is_open()) {
                cout << "Could not find that file." << endl;
                return 1;
        }

        in.close();

        getline(cin, line);
        while(!cin.eof()) {

                lines++;

                chars += line.length() + 1; // does the addition of 1 for the new line

                istringstream line_string(line);
                while (line_string >> word)
                        words++;

                getline(cin, line);
        }

        cout << lines << ' ' << words << ' ' << chars << endl;
}
Last edited on
Just ask the user to type the filename and then read the entire line into a string. Then, open the file using that string as the filename.

By the way, do not loop on EOF - it doesn't work as you expect. Google it. The short story is that you should loop on the input operation itself and almost never check for EOF.
Topic archived. No new replies allowed.