【问题标题】:Passing command line arguments传递命令行参数
【发布时间】:2010-03-02 05:45:46
【问题描述】:

好的,我已经稍微更新了我的代码,但我仍然不确定如何使用我传递的命令行参数向量。我尝试像下面的代码一样设置它,但它不会编译。它给了我找不到 argc 和 argv 的错误:

1>c:\users\chris\documents\visual studio 2008\projects\cplusplustwo\cplusplustwo\application.h(32):错误 C2065:'argc':未声明的标识符 1>c:\users\chris\documents\visual studio 2008\projects\cplusplustwo\cplusplustwo\application.h(32) : error C2065: 'argv' : undeclared identifier

main.cpp

#include "application.h"

int main(int argc,char *argv[]){
    vector<string> args(argv, argv + argc);
    return app.run(args);    
}

应用程序.h

#include <boost/regex.hpp>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "time.h"
using namespace std;



class application{
private:
    //Variables
    boost::regex expression;
    string line;
    string pat;
    string replace;
    int lineNumber;
    char date[9];
    char time[9];


    void commandLine(vector<string> args){
        string  expression="";    // Expression
        string  textReplace="";   // Replacement Text
        string  inputFile="";     // Input File
        string  outputFile="";    // Output Directory
        int optind=1;
        // decode arguments
        for(vector<string>::iterator i = args.begin(); i != args.end(); ++i){
            while ((optind < argc) && (argv[optind][0]=='-')) {
                string sw = argv[optind];
                if (*i == "-e") {
                    optind++;
                    expression = argv[optind];
                }
                else if (*i == "-t") {
                    optind++;
                    textReplace = argv[optind];
                }
                else if (*i == "-i") {
                    optind++;
                    inputFile = argv[optind];
                }
                else if (*i == "-o") {
                    optind++;
                    outputFile = argv[optind];
                }
                else{
                    cout << "Unknown switch: " 
                        << argv[optind] << "Please enter one of the correct parameters:\n" 
                        << "-e + \"expression\"\n-t + \"replacement Text\"\n-i + \"Input File\"\n-o + \"Onput File\"\n";
                    optind++;
                }
            }
        }
    }
    //Functions
    void getExpression(){
        cout << "Expression: ";
        getline(cin,pat);
        try{
            expression = pat;
        }
        catch(boost::bad_expression){
            cout << pat << " is not a valid regular expression\n";
            exit(1);
        }
    }

    void boostMatch(){
        //Define replace {FOR TESTING PURPOSES ONLY!!! REMOVE BEFORE SUBMITTING!!
        replace = "";
        _strdate_s(date);
        _strtime_s(time);
        lineNumber = 0;
        //Files to open
        //Input Files
        ifstream in("files/trff292010.csv");
            if(!in) cerr << "no file\n";
        //Output Files
        ofstream newFile("files/NEWtrff292010.csv");
        ofstream copy("files/ORIGtrff292010.csv");
        ofstream report("files/REPORT.dat", ios.app);
        lineNumber++;
        while(getline(in,line)){
            lineNumber++;
            boost::smatch matches;
            copy << line << '\n';
            if (regex_search(line, matches, expression)){
                for (int i = 0; i<matches.size(); ++i){
                    report << "Time: " << time << "Date: " << date << '\n'
                        << "Line " << lineNumber <<": " << line << '\n';
                    newFile << boost::regex_replace(line, expression, replace) << "\n";

                }
            }else{
                newFile << line << '\n';
            }
        }
    }

public:
    void run(vector<string> args){
        commandLine(vector<string> args);
        getExpression();
        boostMatch();
    }
};

原帖

我想将命令行参数从 main 中传递出去。这是高级 C++ 课程的作业。我需要使用向量传递命令行,但我不确定我是否正确地做所有事情。我会像我一样将它传递给向量吗?还有一个 copy() 命令可以用来将命令行参数复制到向量而不是 pushback 中吗?

main.cpp

#include "application.h"

int main(int argc,char *argv[]){
    vector<string> args;
    application app;
    for (int i=1;i<argc;i++){
        args.push_back(argv[i]);
    }
    app.run(args);
    return(0);
}

应用程序.h

#include <boost/regex.hpp>
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include "time.h"
    using namespace std;

class application{
private:
    //Variables
    boost::regex expression;
    string line;
    string pat;
    string replace;
    int lineNumber;
    char date[9];
    char time[9];


    void commandLine(vector<string> args){
        string  expression="";    // Expression
        string  textReplace="";   // Replacement Text
        string  inputFile="";     // Input File
        string  outputFile="";    // Output Directory
        int optind=1;
        // decode arguments
        for(vector<string>::iterator i = args.begin(); i != args.end(); ++i){
            while ((optind < argc) && (argv[optind][0]=='-')) {
                string sw = argv[optind];
                if (*i == "-e") {
                    optind++;
                    expression = argv[optind];
                }
                else if (*i == "-t") {
                    optind++;
                    textReplace = argv[optind];
                }
                else if (*i == "-i") {
                    optind++;
                    inputFile = argv[optind];
                }
                else if (*i == "-o") {
                    optind++;
                    outputFile = argv[optind];
                }
                else{
                    cout << "Unknown switch: " 
                        << argv[optind] << "Please enter one of the correct parameters:\n" 
                        << "-e + \"expression\"\n-t + \"replacement Text\"\n-i + \"Input File\"\n-o + \"Onput File\"\n";
                    optind++;
                }
            }
        }
    }
    //Functions
    void getExpression(){
        cout << "Expression: ";
        getline(cin,pat);
        try{
            expression = pat;
        }
        catch(boost::bad_expression){
            cout << pat << " is not a valid regular expression\n";
            exit(1);
        }
    }

    void boostMatch(){
        //Define replace {FOR TESTING PURPOSES ONLY!!! REMOVE BEFORE SUBMITTING!!
        replace = "";
        _strdate_s(date);
        _strtime_s(time);
        lineNumber = 0;
        //Files to open
        //Input Files
        ifstream in("files/trff292010.csv");
            if(!in) cerr << "no file\n";
        //Output Files
        ofstream newFile("files/NEWtrff292010.csv");
        ofstream copy("files/ORIGtrff292010.csv");
        ofstream report("files/REPORT.dat", ios.app);
        lineNumber++;
        while(getline(in,line)){
            lineNumber++;
            boost::smatch matches;
            copy << line << '\n';
            if (regex_search(line, matches, expression)){
                for (int i = 0; i<matches.size(); ++i){
                    report << "Time: " << time << "Date: " << date << '\n'
                        << "Line " << lineNumber <<": " << line << '\n';
                    newFile << boost::regex_replace(line, expression, replace) << "\n";

                }
            }else{
                newFile << line << '\n';
            }
        }
    }

public:
    void run(vector<string> args){
        commandLine(vector<string> args);
        getExpression();
        boostMatch();
    }
};

【问题讨论】:

    标签: c++ command-line vector


    【解决方案1】:

    我只想写:

    vector<string> args(argv + 1, argv + argc + !argc);
    

    这将排除argv[0],但即使argc == 0(在Linux 下可能,也可能在其他操作系统下也可能)以某种方式是健壮的。

    【讨论】:

    • 在传入参数之前,您将如何纠正 main 中的原始向量?
    • @shinjuo:构造一个向量args,一次性使用所有命令行参数对其进行初始化。 (对不起,我不知道如何很好地阅读您的评论。)
    • 只是为了确保我理解正确,我可以删除 main 中的所有 pushback 并使用它吗?
    • @shinjuo:是的,没错。不过,别忘了,如果你想排除argv[0],你必须自己安排。
    • @shinjuo:例如,你可以这样做:vector&lt;string&gt; args(argv + 1, argv + argc),但如果argc == 0(可能在 Linux 下,也可能在其他操作系统下),那么你会调用未定义的行为。
    【解决方案2】:

    argv 和 argc 是传递给 main 的参数。在您的函数中,您应该使用 args[i] 和 args.length()

    【讨论】:

    • 我不确定我知道你在说什么地方使用这些?
    • 在您的应用程序方法中使用 args 向量而不是 argc 和 argv 变量。
    【解决方案3】:

    application::commandLine()args 为参数,但它引用了argcargv,它们不在作用域内。如果您查看来自编译器的实际错误消息,它应该包含一个文件名和行号,可以直接指向错误的位置。当就错误消息寻求帮助时,请发布实际的错误消息而不是解释它。

    【讨论】: