簡體   English   中英

來自輸入文件的字符串向量的填充向量

[英]Fill vector of string vectors from input file

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

我在一個函數中有這樣的東西要讀入單詞,但是我一直收到編譯器錯誤,說我無法推回字符串,所以我知道我走錯了路。 任何幫助將不勝感激。

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);
  }

如果 words 是vector<vector<string>>那么words[i][j]正在訪問string 你可能想要做的是words[i][j] = tempWord; . string也有一個函數.push_back()但需要一個char ,這就是為什么你得到的錯誤是你不能 push_back 一個字符串, string s 的push_back()用於將字符附加到字符串。 同樣取決於你如何聲明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;
}

暫無
暫無

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

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