簡體   English   中英

導入csv時出現分段錯誤11錯誤

[英]segmentation fault 11 error while importing csv

我正在做一個函數importcsv(),它接受一個文件名並輸出一個2D數組。 出於某種原因,每當我使用以下版本的importcsv()時,編譯器都會平穩運行,但是可執行文件始終會返回“分段錯誤:11”錯誤。

typedef vector<vector<double> > matrix;

matrix importcsv(string filename)
{
   ifstream myfile (filename);  //Constructs a stream, and then asssociates the stream with the file "filename"

   matrix contents; // Vector which will store the contents of the stream.
   int i, j;
   while(!myfile.eof())
   {
       if(myfile.get()==','){++j;}
       else if(myfile.get()=='\n'){++i; j=0;}
       else{
        contents[i][j]=2;}
   }
   return contents;
}

誰能找到錯誤的根源? 順便說一句,我有以下標題:

#include <fstream>
#include <iostream>
#include <array>
#include <vector>
using namespace std;

由於沒有為contents分配內存,因此出現“ segmentation fault:11”。 僅當contents包含contents[i][j]才有效。

您可以將讀取文件和將矩陣構造為多個部分:

  1. 讀取一行中的所有數字並將其視為一行contents
  2. 從該行讀取一個數字並將其視為一行的一列。

這樣,可以簡化程序。 這也可以幫助您輕松地找出問題並加以解決。

typedef vector<vector<double> > matrix;

double readNextNumber(std::istream& str)
{
   double n = 0.0;
   str >> n;

   // Skip until we get ',' or '\n'
   while (str)
   {
     int c = str.getc();
     if ( c == ',' || c == '\n' || c == EOF )
        break;
   }
   return n;
}

std::vector<double> importRow(std::ifstram& myfile)
{
   std::string line;
   std::vector<double> row;

   // Read a line as a string.
   // Then parse the string using std::istringstream.
   // When you have finished parsing the line, you know
   // you have finished constructing a row of the matrix.
   std::getline(myfile, line);
   if ( myfile )
   {
      std::istringstream str(line);
      while (str)
      {
         double n = readNextNumber(str);
         if (str)
         {
            row.push_back(n);
         }
      }
   }
   return row;
}

matrix importcsv(string filename)
{
   ifstream myfile (filename);  //Constructs a stream, and then asssociates the stream with the file "filename"

   matrix contents; // Vector which will store the contents of the stream.
   while(!myfile.eof())
   {
       std::vector<double> row = importRow(myfile);
       if (myfile)
       {
          contents.push_back(row);
       }
   }
   return contents;
}

您尚未定義contents的大小。 因此,默認情況下,它將是0元素的vector 因此,對operator[]的調用將導致分段錯誤。

在這里實施其他人的建議時,快速解決方案是在將每個值讀入數組之前使用resize():

//WARNING: THIS PROGRAM UTILIZES C++11
#include <fstream>
#include <iostream>
#include <array>
#include <vector>
#include <cctype>
#include <thread>
using namespace std;
typedef vector<vector<double> > matrix;

matrix importcsv(string filename)
{
    ifstream myfile ("wavelengthtorgb.csv");  //Constructs a stream, and then asssociates the stream with the file "filename".
    matrix contents {{0.0}};
        char nextchar; double data; int i,j;

    while(!myfile.eof())
    {
    myfile.get(nextchar);
        if(nextchar==',')
        {
            ++j; 
            contents[i].resize(j+1); 
            cout<<"encountered a comma."<<" contents is now " <<i+1<<" x "<<j+1<<'\n';
        }
        else if(isspace(nextchar))
        {
            myfile.get(); //You might not need this line - first run with this line, and if there is an error, delete it, and try again.
            ++i; 
            contents.resize(i+1);
            j=0; 
            contents[i].resize(j+1);
            cout<<"encountered a carriage return."<<" contents is now " <<i+1<<" x "<<j+1<<'\n';
        }
        else
        {
            myfile.unget();
            myfile >> data;
            contents[i][j]=data;
            cout<< "encountered a double."<<" contents("<<i<<','<<j<<")="<<data<<'\n';
        }
    }
    return contents;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM