从.txt文件到c ++中的向量表

时间:2015-11-24 23:30:59

标签: c++ vector multiple-columns

我有一个文本文件,格式如下:

string1   int1   int6
string2   int2   int7
string3   int3   int8
string4   int4   int9
string5   int5   int10

第一列包含字符串,第二列和第三列包含整数。

我想将每列放在一个单独的向量中,我该怎么做?

2 个答案:

答案 0 :(得分:2)

像这样:

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

std::vector<std::string> v1;
std::vector<int> v2, v3;

for (std::string line; std::getline(infile, line); )
{
    std::istringstream iss(line);

    std::string s;
    int a, b;

    if (!(iss >> s >> a >> b >> std::ws) || iss.get() != EOF)
    {
        std::cerr << "Error parsing line '" << line << "', skipping\n";
        continue;
    }

    v1.push_back(std::move(s);
    v2.push_back(a);
    v3.push_back(b);
}

答案 1 :(得分:0)

首先,你需要逐行阅读文件:

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

std::ifstream file;
std::string line;
std::vector<std::string> lines;
file.open("myfile.txt");

while (std::getline(file, line))
    lines.push_back(line);

然后你需要将单词/整数分开(我假设它们被分开 空格):

size_t pos = 0;
int oldpos = 0;
std::vector<std::string> words;

for (int i = 0; i < lines.size(); ++i)
{
    pos = lines.at(i).find_first_of(' ', oldpos);

    while (pos != std::string::npos)
    {
        words.push_back(lines.at(i).substr(oldpos, pos - oldpos));
        oldpos = pos + 1;
        pos = lines.at(i).find_first_of(' ', oldpos);
    }

    words.push_back(lines.at(i).substr(oldpos, pos - oldpos));

    oldpos = 0;
}

然后你需要将这个大向量的内容传递给3个较小的向量:

std::vector<std::string> strings;
std::vector<int> ints1;
std::vector<int> ints2;

for (int j = 0; j < words.size(); j += 3)
{
    strings.push_back(words.at(j));
    ints1.push_back(std::atoi(words.at(j + 1).c_str()));
    ints2.push_back(std::atoi(words.at(j + 2).c_str()));
}

我认为此代码优于上述答案的原因是因为首先,它允许您选择分隔符,例如如果你使用逗号而不是空格。它也是可扩展的 - 只需添加几个向量并将j + = 3更改为你拥有的多个向量。

相关问题