使用此代码,我可以读取数据文件并将其放入数组中。但是现在我想在将文件作为参数的函数中转换此代码。有人知道我该怎么做吗?

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

最佳答案

像这样吗

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


根据您的问题,函数将以字符串形式接收文件名,并且也会传递矢量。

另一种选择是将文件作为流传递:

void somebody_function(std::istream& input_file,
                       vector< vector< double > >& v)
{
 //...
}

10-04 14:58