我想在 C++ 中创建一个函数来读取一个以该文件作为参数的文件,但是我在编译程序时遇到了问题

I want to create a function in c++ to read a file having the file as an argument, but I have problems when I compile the program

这是读取文件的函数

void read_function(istream& filename, vector< vector<double> >& v)
{
//vector<vector<double> > v;
    if (filename)
    {
        string linea; 
        int i = 0;
        while (getline(filename, linea))
        {
            v.push_back(vector<double>());
            stringstream split(linea);
            double value;
            while (split >> value)
            {
                v.back().push_back(value);
            }           
        }
    }
};

主要功能

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

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

string program_name = argv[0];
ifstream input;
input.open(argv[1]);

vector< vector<double> > array;

for (int i = 0; i < array.size(); i++) 
{             
    for (int j = 0; j < array[i].size(); j++) 
        cout << read_function(argv[1], array) << '\t';    
        cout << endl;
}

return 0;
}

当我编译代码时,我收到以下错误消息

错误:从类型为“const char*”的表达式对类型为“std::istream& {aka std::basic_istream&}”的引用的初始化无效 cout << read_function(argv[1], 数组) << '\t';

错误:传递‘void read_function(std::istream&, std::vector >&)’的参数 1 void read_function(istream& filename, vector< vector >& v)

请不要误会,但是您在代码中犯的错误看起来像这样对于您的编程技能水平来说可能是一项太难的任务。

你犯了几个错误:

  1. 您(有点)在 main 中声明 input 但尝试在 read_function

  2. 中使用它
  3. 您在getline中使用的参数不正确

  4. read_function的第一个参数是ifstream类型而不是char*

  5. getlineifstream

  6. 的成员函数
  7. read_function returns 没什么,所以 cout<<read_function(...) 不正确

我建议在尝试使用更复杂的东西(例如 sstreamfstreamvector 之前,您首先要尝试了解如何调用函数、参数及其类型是,什么是对象以及如何访问其成员。

我纠正了你的错误,下面的代码只从你的输入文件中读取数字,没有字符。我认为这是您的目标,因为您使用了 double 向量。也有更优雅的方法来做到这一点,但我试图尽可能接近你的代码。

代码:

#include<fstream>
#include<iostream>
#include<vector>
#include<sstream>

using namespace std;

void read_function(char* filename, vector< vector<double> >& v)
{
    int maxNumberOfCharsPerLine=1000;
    ifstream input;
    input.open(filename);
    if(input.is_open())
    {
        char* inputChar;
        string linea; 
        while (input.getline(inputChar, maxNumberOfCharsPerLine))
        {
            linea=inputChar;
            v.push_back(vector<double>());
            stringstream split(linea);
            double value;
            while (split >> value)
            {
                v.back().push_back(value);
            }           
        }
    }
    input.close();
}

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

    if (argc < 2)
    {   
        cerr << "no input file's name\n"<< endl;
    }   

    vector< vector<double> > array;
    read_function((char*)argv[1], array); 

    for (int i = 0; i < array.size(); i++) 
    {             
        for (int j = 0; j < array[i].size(); j++)  
        {
            cout << array[i][j] <<" ";
        }
        cout << endl;
    }
    return 0;
}