将命令行参数程序转换为菜单驱动程序

时间:2012-05-07 00:49:54

标签: c++

我做了一个程序,它接受命令行争论来运行它。我现在正在尝试将菜单驱动程序作为其“改进”的一部分。我用了,

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

原文中的论点是:

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

以下是我现在所做的事情,我知道这是不正确的:

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;

由于我的所有程序都基于char * argv []如何将它们转换为字符串或者如何将变量分配给参数以便读取它们?

我很欣赏所有的答案,但他们似乎正朝着我想要摆脱的方向前进。 OLD程序使用命令行争论。我该怎么做:

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

这就是我想要做的。如果我不清楚,我很抱歉。

3 个答案:

答案 0 :(得分:4)

这可能会有所帮助。

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] ... 

}

答案 1 :(得分:0)

将命令行参数转换为字符串:

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

我从'1'开始,因为'0'是程序名称:


让他们进入vars,也许:

// 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];      

答案 2 :(得分:0)

要从const char *获取std::string,请使用std::string::c_str()

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