2017-01-02 49 views
1

我在創建通過讀取文本文件中的值創建的字符串的2D向量時遇到了一些麻煩。我最初認爲我需要使用一個數組。然而,我已經認識到,矢量將更適合我想要實現的。從文本文件中創建2D字符串向量

這裏是我到目前爲止的代碼:

我初始化向量全球範圍內,但沒有給它的行或列的數量,因爲我想,當我們讀取文件要進行確定:

所謂的文件中
vector<vector<string>> data; 

測試數據「測試」目前看起來是這樣的:

test1 test2 test3 
blue1 blue2 blue3 
frog1 frog2 frog3 

然後我有打開的文件,並嘗試通過琴絃的text.txt從複製到一個功能向量。但是,當我嘗試在我的主函數中檢查我的向量的大小時,它返回值'0'。

int main() 
{ 
    cout << data.size(); 
} 

我想我只需要一雙清新的眼睛告訴我我要去哪裏錯了。我覺得問題在於createVector函數,雖然我不是100%確定的。

謝謝!

+0

[請閱讀爲什麼在一個循環中使用EOF()不好(http://stackoverflow.com/questions/5605125/why- is-iostreameof-inside-a-loop-condition-considered-wrong) – PaulMcKenzie

+0

*但是沒有給出它的行數或列數,因爲我想在讀取文件時確定它:* - 那麼爲什麼你在你的'createVector'函數中硬編碼'5'和'3'? – PaulMcKenzie

+0

感謝您的回覆保羅。我知道列的最大數量是3,但我不知道行數(因爲這可以通過程序中的其他功能(即添加和刪除元素)來更改)。 – GuestUser140561

回答

1

您應該先使用std::getline來獲取數據行,然後從行中提取每個字符串並添加到您的向量中。這避免了註釋中指出的while -- eof()問題。

下面是一個例子:

#include <string> 
#include <iostream> 
#include <vector> 
#include <sstream> 

typedef std::vector<std::string> StringArray; 

std::vector<StringArray> data; 

void createVector() 
{ 
    //... 
    std::string line, tempStr; 
    while (std::getline(myReadFile, line)) 
    { 
     // add empty vector 
     data.push_back(StringArray()); 

     // now parse the line 
     std::istringstream strm(line); 
     while (strm >> tempStr) 
      // add string to the last added vector 
      data.back().push_back(tempStr); 
    } 
} 

int main() 
{ 
    createVector(); 
    std::cout << data.size(); 
} 

Live Example

+0

謝謝你花時間解釋保羅,它真的爲我解決了問題!得到它完美的工作。 – GuestUser140561