c++ - 如何从文件中生成 "2 dimentional vector"行 X 字?

标签 c++ string vector ifstream

我有一个输入文本文件,每一行都有不同的信息,但我需要能够从特定行中快速选择特定单词几百次,所以我需要一个字符串 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/

相关文章:

c++ - 使用深度图

python - 删除列表中字符串中的日期和年份重复项

java - 为什么这两个字符串的编辑距离得分如此低?

c++ - 如何从 cv::Vec3f 转换为 float 类型?

c++ - 带 vector 指针的链表

c++ - 修复错误的 JSON 数据

c++ - 将特征 Affine3d 转换为 Affine2d

c++ - std::vector 中包含的类中的 STL 字符串成员

c++ - 获取 LNK1104 : cannot open file "libssl.obj"

java - 计算平均值,字符串标记化练习