[英]Passing a command line argument input file to a class to parse
There is probably a very simple solution to my problem but I am having some problems passing an input file (from command line arguments) into a class for parsing. 解决我的问题的方法可能很简单,但是在将输入文件(从命令行参数)传递到类进行解析时遇到了一些问题。
Here is the relevant part of my main.cpp code: 这是我的main.cpp代码的相关部分:
#include <iostream>
#include <chrono>
#include "SortingCompetition.h"
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "Invalid arguments" << std::endl;
std::cerr << "Usage: ./a.out <input file> <output file>" << std::endl;
return 1;
}
SortingCompetition sorter(argv[1]);
return 0;
}
Here is the SortingCompetition.h file: 这是SortingCompetition.h文件:
#ifndef SORTINGCOMPETITION_H_
#define SORTINGCOMPETITION_H_
#include <string>
#include <vector>
using namespace std;
class SortingCompetition{
private:
string& input_;
vector<string> data_;
public:
SortingCompetition(const string& inputFileName);
void setFileName(const string& inputFileName);
bool readData();
bool prepareData();
void sortData();
void outputData(const string& outputFileName);
};
#endif
All the functions must remain the same here. 这里所有功能必须保持不变。 ie
SortingCompetition(const string& inputFileName);
即
SortingCompetition(const string& inputFileName);
must stay that way... I cannot remove the const
or anything else. 必须保持这种方式...我无法删除
const
或其他任何内容。
Here is the relevant implementation of SortingCompetition: 这是SortingCompetition的相关实现:
#include "SortingCompetition.h"
SortingCompetition::SortingCompetition(const string& inputFileName){
input_ = inputFileName;
}
void SortingCompetition::setFileName(const string& inputFileName){
input_ = inputFileName;
}
This is where I'm getting problems, I'm not passing the input file from the command argument to the private variable correctly. 这是我遇到问题的地方,我没有将输入文件从命令参数正确传递给私有变量。 I've searched for quite a while, but cannot find a solution.
我已经搜索了很长时间,但是找不到解决方案。
You're passing it correctly, but you're storing a reference to temporary. 您正确传递了它,但存储的是对临时文件的引用。 This is the problem.
这就是问题。
Change: 更改:
class SortingCompetition{
private:
string input_; // THIS LINE
vector<string> data_;
This copies the value so it doesn't matter that the parameter to the constructor (or setFilename
) was only a temporary 这将复制值,因此构造函数的参数(或
setFilename
)只是临时的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.