我有一个输入文本文件,每一行都有不同的信息,但我需要能够从特定行中快速选择特定单词几百次,所以我需要一个字符串 vector vector 。
我有 2 个起点,但都不知道如何继续。
std::vector<std::string> lines;
std::string line;
while ( std::getline(input, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
将它分成几行
或
std::string word;
while (in_str >> word ) {
input.push_back(word);
}
将它分成单词
最佳答案
您可以结合两种方法:-)
首先,您使用 getline 获取整行,然后将该行视为 std::istringstream(本质上是一个普通的 istream)的来源,并将输入拆分为单词。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main(void) {
std::vector<std::vector<std::string> > lines;
std::string line;
while ( std::getline(std::cin, line) ) {
if ( !line.empty() ) {
std::vector<std::string> words;
std::string word;
std::istringstream is(line);
while (is >> word)
words.push_back(word);
lines.push_back(words);
}
}
std::cout << "The word at line 3, pos 2 is \"" << lines[2][1] << '"' << std::endl;
return 0;
}
这给了我以下内容:
abc def gdf qwe asd zxc qaz wsx edc The word at line 3, pos 2 is "wsx"
关于c++ - 如何从文件中生成 "2 dimentional vector"行 X 字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609020/