Trouble with Command Line Argument

Hi, I'm having some issues reading in a file from the command line argument. Basically I have a file with text from chapter one of a story. I am supposed to read in the file and then find the bigrams (pairs of words) in the file.

However there are multiple files of text with different passages. Therefore I have to take the name of a file as a command line argument.

Can anyone tell me why I keep getting the error that my file did not open?

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
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <utility> 
using namespace std;


typedef map<pair<string, string>, int> StrPairIntMap;
typedef map<string, int>  StrIntMap;
typedef map<pair<string, string>, double> StrPairDoubleMap;

StrPairDoubleMap CalcBigrams(ifstream&);
void PrintBigrams(StrPairDoubleMap&, string, string);
int main(int argc, char* argv[])
{

    ifstream file(argv[1]); // delcare and open file

    if(!file) // check if file opened
    {
        cout << "FILE NOT OPENED";
        return 0;
    }

    string w1, w2;
    StrPairDoubleMap m3 = CalcBigrams(file);
    while(true)
    {
        cout << "Enter two words (q to quit): ";

        cin >> w1;
        if(w1 == "q") break;

        cin >> w2;
        if (w2 == "q")break;
        PrintBigrams(m3, w1, w2);
    }

    file.close();

    return 0;
}

//Function Definitions...
Last edited on
> why I keep getting the error that my file did not open?

The file may be in a different directory. Specify the fully qualified path to the file.

Printing out the name of the file would help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main( int argc, char* argv[] )
{
    if( argc > 1 )
    {
        std::cout << "attempting to open file: '" << argv[1] << "'\n" ;
        
        std::ifstream file( argv[1] ) ;
        if( !file.is_open() )
        {
            std::cout << "could not open file\n" ;
            return 1 ;
        }

        // ... 


I've tried your suggestion and tinkered with my code but the program is still not doing what i need it to do.
What does this print out? std::cout << "attempting to open file: '" << argv[1] << "'\n" ;
Thank you for your suggestion. I've actually tried a different approach of having the user cin and then storing that into a string object and using that to open file and it worked out pretty well.
Topic archived. No new replies allowed.