c_sharp
c_sharp

Reputation: 281

converting command line arguments program to menu driven program

I did a program that took command line arguements to run it. I am now trying to do a menu drive program as part of its "improvement." I used,

int main(int argc, char * argv[])

in the original where the arguements were:

char * startCity = argv[1];
char * endCity = argv[2];
in.open(argv[3],ios::in); //<----file name went here

Here is what I did now and I know it is incorrect:

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

int menuChoice;
string startCity;
string endCity;
string fileName;
ifstream in;

cout<<"Welcome to J.A.C. P2\n"
  "\n"
  "This program will find the shortest path\n"
  "from One city to all other cities if there\n"
  "is a connecting node, find the shortest path\n"
  "between two cities or find the shortest\n"
  "between three or more cities.\n"<<endl;

cout<<"Please make a choice of what you would like to do:\n"<<endl;

cout<<"  1------> Shortest Path between 2 cities.\n"
      "  2------> Shortest Path between 3 or more cities.\n"
      "  3------> Shortest Path from 1 city to all.\n"
      "  9------> Take your ball and go home!\n"<<endl;
cout<<"Waiting on you: "; cin>>menuChoice;

switch (menuChoice) {
    case 1:
        cout<<"Enter the starting city: ";
        cin>>StartCity;
        cout<<"\nEnter the ending city: ";
        cin>>EndCity;
        cout<<"\nEnter the name of the file: ";
        cin>> fileName;

    break;

Since all of my program is based on char * argv[] How can I convert those into strings OR how can I assign variables to the arguements in order to read them in?

I appreciate all the answers but they seem to be going in the direction I am trying to get away from. The OLD program used command line arguements. How can I do this:

string StartCity = char * argv[1];
string EndCity = char * agrv[2];
string filename = in.open(argv[3],ios::in);

That is what I am trying to do. I am sorry if I did not make myself clear.

Upvotes: 1

Views: 896

Answers (3)

Qaz
Qaz

Reputation: 61970

To get a const char * from a std::string, use std::string::c_str().

fstream file;
string s = "path\\file.txt";
file.open (s.c_str(), ios::in);

Upvotes: 0

matiu
matiu

Reputation: 7725

to convert the command line arguments to strings:

std::vector<std::string> args(argc);
for (int i=1; i<argc; ++i)
   args[i] = argv[i];

I start at '1' because '0' is the program name:


to get them into vars, maybe:

// Make sure we're not accessing past the end of the array.
if (argc != 4) {
    std::cout << "Please enter three command line arguments" << std::endl;
    return 1;
}

string startCity = argv[1];
string endCity = argv[2];
string fileName = argv[3];      

Upvotes: 0

bisarch
bisarch

Reputation: 1398

This might help.

int main (int argc, char ** argv)
{
          std::vector<std::string> params(argv, argv + argc);       
          //Now you can use the command line arguments params[0], params[1] ... 

}

Upvotes: 4

Related Questions