1

我做了一个程序,它需要命令行参数来运行它。我现在正在尝试做一个菜单驱动程序,作为其“改进”的一部分。我用了,

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);

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

4

3 回答 3

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

}
于 2012-05-07T01:17:18.757 回答
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];      
于 2012-05-07T01:21:19.257 回答
0

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

fstream file;
string s = "path\\file.txt";
file.open (s.c_str(), ios::in);
于 2012-05-07T01:27:15.520 回答