将.txt文件中的表转换为c++中的矢量

table from .txt file into vectors in c++

本文关键字:c++ txt 文件 转换      更新时间:2023-10-16

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

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

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

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

如此:

#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 << "', skippingn";
        continue;
    }
    v1.push_back(std::move(s);
    v2.push_back(a);
    v3.push_back(b);
}

首先需要逐行读取文件:

#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更改为您拥有的向量数量。