2017-01-02 92 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