2017-08-05 56 views
-2

我知道這裏有很多類似標題的問題,但似乎沒有人爲我工作。 我有這樣的txt文件的:將.txt文件存儲爲char * 2d向量C++

tree pine 
color blue 
food pizza 

,我想存儲在一個char * 2D矢量的項目,如

vector<vector<char*>> data; 
.. 
.. 
data[0][0] = tree 
data[0][1] = pine 
data[1][1] = blue 
ecc 

這是代碼:

// parse configuration file 
bool Configuration::fileParser(char* filename) 
{ 
    vector<vector<char*>> data; 
    fstream fin("data/setup.txt"); 
    string line; 
    while (fin && getline(fin, line)) 
    { 
     vector<char*> confLine; 
     char* word = NULL; 
     stringstream ss(line); 
     while (ss && ss >> word) 
     { 
      confLine.push_back(word); 
     } 
     data.push_back(confLine); 
    } 
    storeData(data); 
    return 0; 
} 

但是,當我運行代碼引發異常。

Exception thrown: write access violation. 

我該如何解決這個問題? 謝謝

+0

「我該如何解決這個問題?」首先使用'std :: string'。 – DimChtz

+0

你使用什麼編譯器? – Aan

+0

在哪一行/哪個函數是拋出的異常? 'storeData'如何實現?我們不知道您項目的背景,因此您必須儘可能提供完整的信息。 – meowgoesthedog

回答

0

聲明:我手邊沒有編譯器來測試下面的代碼與文件,但它應該工作。

這裏是我使用的參考:Parse (split) a string in C++ using string delimiter (standard C++)

描述:基本上下面的代碼解析在文件逐行然後分配第一字和第二字入載體所傳遞的。請注意,我在示例中使用了string(s),因爲我不想考慮內存管理。

#pragma once 
#include <vector> 
#include <fstream> 
#include <string> 

void Configuration::fileParser(string fileName) 
{ 
    vector<vector<string>> data; 

    ifstream configFile(fileName); 
    string line, token; 
    string delimiter = " "; 
    size_t pos; 
    if (configFile.is_open()) 
    { 
     int n = 0; 
     while (getline(configFile, line)) 
     { 
      if (!line || line == "") 
       break; //added as a safety measure 
      pos = 0; 
      if ((pos = line.find(delimiter)) != string::npos) 
      { 
       token = line.substr(0, pos); 
       data[n][0] = token; //add first word to vector 
       line.erase(0, pos + delimiter.length()); 
      } 
      if ((pos = line.find(delimiter)) != string::npos) 
      { 
       token = line.substr(0, pos); 
       data[n][1] = token; //add second word to vector 
       line.erase(0, pos + delimiter.length()); 
      } 
      n++; 
     } 
    } 
    storeData(data); 
} 
1

您尚未分配任何可寫入數據的存儲器。你需要類似char* word = new char[50];。但只需使用std::string它更安全,更容易。