How to pass parameter in stdin

Jan 18, 2009 at 3:03am
Hi all,

Currently this program of mine hard code
the input data (i.e. mydata.txt) inside it.

How can I modify it so that I can pass parameter for input file
when executing the program in command line?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    ifstream myfile ("mydata.txt");
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}


I am thinking like this command line

 
$ ./mycode  mydata2.txt
Jan 18, 2009 at 4:53am
I think you make main() take two parameters; int argc and char** argv.

int main(int argc, char** argv) {

argv is an array of C-style strings of the command line parameters, with element 0 being the name used to call the executable. argv is the number of parameters.
Jan 18, 2009 at 7:47am
Hi zhude,


Thanks, but then how can I replace "mydata.txt"
in this line?

 
ifstream myfile ("mydata.txt");


I tried

 
ifstream myfile (argv);


but fail.
Jan 18, 2009 at 9:14am
int main(int argc, char** argv)

In this code, argc is how many parameters are passed to your program, argv contains them. You treat argv as an array:

argv[0] - should contain the command used to execute the program (ie mycode.exe)
argv[1] - will be your first parameter (so hopeflly "mydata2.txt")

Then you need to do something like:

1
2
3
4
5
6
7
8
9
if(argc==2) // if there is a filename passed to it (only 1 extra parameter)
{
// all code goes here
ifstream myfile (argv[1]); // this is opening the file in the parameter
}
else // if 1 extra parameter was not passed
{
cout << "No file specified"; // tell the user they did not enter a file
}


Hope that helps.
Jan 18, 2009 at 1:50pm
thanks chris.
Topic archived. No new replies allowed.