简体   繁体   中英

How to pass data file as an argument into a function in c++?

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;
}

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)
{
 //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM