[英]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.