将.txt文件中的表转换为c++中的矢量
table from .txt file into vectors in c++
我有一个文本文件,格式如下:
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更改为您拥有的向量数量。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 如何修复此iFile以将.txt输出到控制台
- 无法打开.txt文件
- CMakeLists.txt中的命名空间表示法
- Arduino从Txt读取整数
- 如何使用CLion在Mac上创建一个新的.txt文件
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 更正 CMakeList.txt 用于谷歌测试的文件?
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 将生成文件转换为 CMakeLists.txt等效项
- 使用循环将多行写入.txt
- CMake 错误"源似乎不包含 CMakeLists.txt",路径/库连接问题
- C++/autoconf 等效于文档库要求.txt的要求是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上