Передача аргументов командной строки - PullRequest
2 голосов
/ 02 марта 2010

Хорошо, я немного обновил свой код, но я все еще не совсем уверен, как использовать вектор передаваемых аргументов командной строки. Я попытался настроить его, как код, который я имею ниже, но он не будет компилироваться. Это дает мне ошибку, что он не может найти 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): ошибка C2065: 'argv': необъявленный идентификатор

main.cpp

#include "application.h"

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

application.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);
}

application.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();
    }
};

Ответы [ 3 ]

10 голосов
/ 02 марта 2010

Я бы просто написал:

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

Это исключит argv[0], но в некотором смысле это надежно, даже если argc == 0 (возможно под Linux и, возможно, с другими ОС).

2 голосов
/ 02 марта 2010

argv и argc - это параметры, передаваемые в main. В вашей функции вы должны использовать args [i] и args.length ()

1 голос
/ 02 марта 2010

application::commandLine() принимает args в качестве параметра, но относится к argc и argv, которые не входят в область видимости. Если вы посмотрите на фактическое сообщение об ошибке от компилятора, оно должно содержать имя файла и номер строки, которые указывают вам непосредственно на место ошибки. При обращении за помощью с сообщением об ошибке, пожалуйста, напишите фактическое сообщение об ошибке, а не перефразируйте его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...