1

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:

#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:

#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. i.e. SortingCompetition(const string& inputFileName); must stay that way... I cannot remove the const or anything else.

Here is the relevant implementation of 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.

3
  • What's the point where "parsing" is important? I don't think it's related. Commented Oct 2, 2013 at 18:36
  • In the readData function, I'm trying to parse the input file: bool SortingCompetition::readData(){ string temp; input_ >> temp; Commented Oct 2, 2013 at 18:39
  • Oh aha. Is there another question about that then? Commented Oct 2, 2013 at 18:44

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks. But what do I change it to? If I stick a const in there I can't parse it anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.