简体   繁体   English

读取二维数组中的文件

[英]Reading file in 2d array

I am trying in this function to read data from csv file in 2d array but when print the array the output is zero, What is the issue?我正在尝试在此函数中从二维数组中的 csv 文件读取数据,但是当打印数组时输出为零,这是什么问题? The file has 5 rows and 500 columns该文件有 5 行和 500 列

void readFilesToReadings() {
int row = 5;
int col = 10;

int myArray[row][col];
string fileName, BasefileName = "C:/Users/hhh/Desktop/frac/Z500.csv"
//Opening the file
ifstream inputfile(fileName);

if (!inputfile.is_open()) 
cout<<"Error opening file" ;

//Defining the loop for getting input from the file

for (int r = 0; r < row; r++) //Outer loop for rows
{
    for (int c = 0; c < col; c++) //inner loop for columns
    {
      inputfile >> myArray[r][c];  //Take input from file and put into myArray
    }
}

for (int r = 0; r < row; r++)
{
    for (int c = 0; c < col; c++)
    {
        cout << myArray[r][c] << "\t";
    }
    cout<<endl;
}

}

Here's the fixed code, you were only setting BasefileName (which was never used, and fileName was not set, so of course your file open failed. (I've tested with my own csv and they now works):这是固定的代码,您只设置了 BasefileName(从未使用过,也没有设置 fileName,所以您的文件打开当然失败了。(我已经用我自己的 csv 进行了测试,它们现在可以工作了):

void readFilesToReadings() {
   const int row = 5;
   const int col = 10;

   int myArray[row][col];
   string fileName = "C:/Users/hhh/Desktop/frac/Z500.csv";
   
   //Opening the file
   ifstream inputfile(fileName);

   if (!inputfile.is_open())
   {
      cout << "Error opening file";
   }
   else {

      //Defining the loop for getting input from the file

      for (int r = 0; r < row; r++) //Outer loop for rows
      {
          for (int c = 0; c < col; c++) //inner loop for columns
          {
             inputfile >> myArray[r][c];  //Take input from file and put into myArray
          }
      }

      for (int r = 0; r < row; r++)
      {
          for (int c = 0; c < col; c++)
          {
              cout << myArray[r][c] << "\t";
          }
          cout << endl;
      }
   }

} }

Reading stuff from file is not difficult in C++, but there is a pattern you should follow.从文件中读取内容在 C++ 中并不困难,但您应该遵循一种模式。 It is easiest to make yourself a little function to implement this pattern.自己做一个小函数来实现这个模式是最简单的。

#include <fstream>
#include <iostream>
#include <string>

template <typename T, size_t ROWS, size_t COLUMNS>
bool load_readings_from_file( 
    const std::string & filename, 
    T (&array)[ROWS][COLUMNS], 
    char delimiter = ',' )
{
    std::ifstream f( filename );
    for (size_t row = 0;  row < ROWS;  row++)
    {
        for (size_t column = 0;  column < COLUMNS;  column++)
        {
            f >> std::ws;
            if (f.peek() == delimiter) f.get();
            f >> array[row][column];
        }
    }
    return (bool)f;
}

I have used templates so you can pass any size array you want to it, but you could easily hardcode the array type (size) in the global namespace if you want.我使用了模板,因此您可以将任何大小的数组传递给它,但如果需要,您可以轻松地在全局命名空间中对数组类型(大小)进行硬编码。

using ReadingsArrayType = int[5][10];

bool load_readings_from_file(
    const std::string & filename,
    ReadingsArrayType array,
    char delimiter = ',' )
{
    ...
}

Either way, using it to fill an array from file is about as easy as it looks:无论哪种方式,使用它从文件填充数组都和看起来一样简单:

int main()
{
    constexpr int rows = 5;
    constexpr int cols = 10;
    
    int myReadingsArray[rows][cols];
    
    if (!load_readings_from_file( "C:/Users/hhh/Desktop/frac/Z500.csv", myReadingsArray ))
    {
        std::cerr << "Could not load file!\n";
        return 1;
    }
    
    // Print the matrix
    for (int r = 0;  r < rows;  r++)
    {
        for (int c = 0;  c < cols;  c++)
        {
            std::cout << myReadingsArray[r][c] << "\t";
        }
        std::cout << "\n";
    }
}

(Again, if you use the array type directly: (同样,如果你直接使用数组类型:

int main()
{
    ReadingsArrayType myReadingsArray;

    if (!load_readings_from_file( ... )) ...

As you can see it is much less clear that myReadingsArray is, in fact, an array... So I personally tend to avoid this kind of type aliasing.)正如您所看到的, myReadingsArray实际上是一个数组不太清楚......所以我个人倾向于避免这种类型别名。)

Finally, you should generally avoid using absolute paths for your filenames.最后,您通常应该避免为您的文件名使用绝对路径。 Put the data in the same directory as your executable, or a subdirectory of it.将数据放在与可执行文件相同的目录或其子目录中。 Better yet, let the user supply a filename:更好的是,让用户提供一个文件名:

int main( int argc, char ** argv )
{
    if (argc != 2)
    {
        std::cerr << "usage:\n  myprog FILENAME\n";
        return 1;
    }

    const char * filename = argv[1];

    int myReadingsArray[5][10];

    if (!load_readings_from_file( filename, myReadingsArray )) ...

Creating functions to do stuff is just one step away from applying the full power of C++ to serialize objects for you.创建函数来执行任务只是应用 C++ 的全部功能为您序列化对象的第一步。 You'll get to that a little later.稍后你会谈到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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