2016-05-29 64 views
-1

我真的很感謝這裏的幫助。我需要使用輸入文件中的文本填充字符串向量的向量。我真的不知道如何開始。從輸入文件填充向量的字符串向量

我有這樣的函數來讀取單詞,但我不斷收到編譯器錯誤,說我不能推回一個字符串,所以我知道我在錯誤的軌道上。任何幫助將非常感激。

ifstream input(filename); 

for (int i = 0; i < 4; i++) 
{ 

    for (int j = 0; j < 4; j++) 
    { 
    string line; 
    getline(input, line); 
    stringstream temp(line); 
    string tempWord; 
    temp >> tempWord; 
    words[i][j].push_back(tempWord); 
    } 
+1

可能是'words [i] [j] = tempWord;'? – songyuanyao

+0

你是怎麼聲明'單詞'的? –

+0

它的聲明矢量>字;並通過引用傳遞給我正在使用的函數來嘗試閱讀某些單詞。 – zettaucla

回答

0

如果單詞是一個vector<vector<string>>然後words[i][j]正在訪問string。你可能想要做的是words[i][j] = tempWord;string也有一個功能.push_back(),但需要一個char這就是爲什麼你得到的錯誤是你不能push_back一個字符串,push_back()string s是用於追加字符的字符串。同樣取決於你如何聲明words,如果你沒有給出尺寸,words[i][j]可能會訪問超出範圍,更好的方法是做words[i].push_back(tempWord)。同樣看着你的for循環我不確定你想要從你想要的文件中得到哪些單詞的意圖,但是現在作爲你的代碼,它會在文件的前16行讀取,並將每個單詞的第一個「單詞」放入您的words對象。如果你的意圖是有一個向量的字符串向量,其中每個子向量是一行中的單詞,那麼像下面的東西可能會更好。

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


int main(int argc, char* argv[]) 
{ 
    std::string filename = "testfile.txt"; 
    std::ifstream input(filename.c_str()); 
    if(!input){ 
     std::cerr << "Error in opening file: " << filename << "\n"; 
     return 1; 
    } 
    std::vector<std::vector<std::string> > words; 
    std::string line; 

    while(std::getline(input, line)){ 
     std::stringstream ss; 
     ss << line; 
     std::vector<std::string> row; 
     while (!ss.eof()) { 
      std::string tempStr; 
      ss >> tempStr; 
      row.push_back(tempStr); 
     } 
     words.push_back(row); 
    } 
    //... then do something with words here 
    return 0; 
} 
+0

非常感謝。我真的不知道如何開始。我的程序不斷崩潰,我想這是因爲我的for循環被搞砸了。你是對的,我試圖把分矢量作爲一行/一句話。另外,我如何訪問各種單詞?一個for循環? – zettaucla

+0

'words [0] [0]'將訪問第一行的第一個單詞,'words [0] [1]'將訪問第一行的第二個單詞等等。但是您還應該檢查大小,沒有訪問超出範圍,words.size()會給你行數,單詞[0] .size()會給你第一行中的單詞數量等,或者你可以使用.at(),將訪問具有範圍檢查的元素,因此第一行'words.at(0).at(0)'中的第一個單詞。如果你做了'words.at(5).at(0)',並且文件中沒有6行,你會得到一個std :: out_of_range異常,但是'words [5] [0]'只會出現seg fault –