0

With this code I can read a data file and put it in an array. But now I want to convert this code in a function having the file as an argument. Someone know how I can do that?

int main(int argc, char const *argv[]){

if (argc < 2)
{   
     cerr << "input the name of file\n"<< endl;
}   

string program_name = argv[0];
ifstream input(argv[1]);
vector<vector<double> > v;

if (input)
{
    string line; 
    int i = 0;
    while (getline(input, line))
    {
        if (line[0] != '#')
        {
            v.push_back(vector<double>());
            stringstream split(line);
            double value;
            while (split >> value)
            {
                v.back().push_back(value);
            }           
        }
    }
}

for (int i = 0; i < v.size(); i++) 
{    
         for (int j = 0; j < v[i].size(); j++) 
         cout << v[i][j] << '\t';    
         cout << endl;
}

1 Answer 1

2

Something like this?

void my_function(const std::string& filename,
                 vector< vector<double> >& v)
{
 //...
}

Per your question, the function is receiving the name of the file as a string and the vector is passed as well.

Another alternative is to pass the file as a stream:

void somebody_function(std::istream& input_file,
                       vector< vector< double > >& v)
{
 //...
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Fredifqh: If my answer is helpful, please click on the check mark. BTW, I'm not Louen.
Hi Thomas, I modified the code. But the code is not working. Is the first time that I use this link. I want to show you the new code, but I don't know where I should put it.
If the issue is different than the one you posted, post a new question. Before you post new code, use a debugger to find out where the code is not executing properly.

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.