如何使用两列C 从文本文件中填充向量
how to populate vector from text file with two columns C++
我是C 的新手,并试图在2D平面中创建一个从文本文件读取的点。为此,我首先创建一个由两个称为点的值(x,y)组成的结构。然后将这些点的向量称为VEC。但是,我不确定在文本文件中以三列为单位时如何填充结构数据!第一列只是点的索引,第二列是x数据,第三列是y数据。我不知道VEC的大小,所以我尝试使用push_back()
,这是我到目前为止所拥有的。
int main(){
struct point{
std::vector<x> vec_x;
std::vector<y> vec_y;
};
std::vector<point> vec;
vec.reserve(1000);
push_back();
ifstream file;
file.open ("textfile.txt");
if (textfile.is_open()){
/* want to populate x with second column and y with third column */
}
else std::cout << "Unable to open file";
}
我有以下评论的地方;
while( file >> x )
vec.push_back (x);
while( file >> y )
vec.push_back (y);
很抱歉,如果这很简单,但这对我来说不是!下面发布的是TXT文件的一个示例,只有6个点。
0 131 842
1 4033 90
2 886 9013490
3 988534 8695
4 2125 10
5 4084 474
6 863 25
编辑
while (file >> z >> x >> y){
struct point{
int x;
int y;
};
std::vector<point> vec;
vec.push_back (x);
vec.push_back (y);
}
您可以在循环中使用普通输入操作员>>
:
int x, y; // The coordinates
int z; // The dummy first value
while (textfile >> z >> x >> y)
{
// Do something with x and y
}
至于结构,我建议一些不同的方法:
struct point
{
int x;
int y;
};
然后具有结构的向量:
std::vector<point> points;
在循环中,创建一个point
实例,初始化其x
和y
成员,然后将其推回points
向量。
请注意,上面的代码几乎没有错误检查或容错性。如果文件中存在错误,则更具体地说,如果格式存在问题(例如,一行中的一个额外数字,或一个数字,那么上面的代码将无法处理。为此,您可以使用std::getline
读取整行,将其放入std::istringstream
中,然后从字符串流中读取x
和y
变量。
将所有内容放在一起,工作代码的简单示例(不处理无效输入)将是
之类的#include <fstream>
#include <vector>
// Defines the point structure
struct point
{
int x;
int y;
};
int main()
{
// A collection of points structures
std::vector<point> points;
// Open the text file for reading
std::ifstream file("textfile.txt");
// The x and y coordinates, plus the dummy first number
int x, y, dummy;
// Read all data from the file...
while (file >> dummy >> x >> y)
{
// ... And create a point using the x and y coordinates,
// that we put into the vector
points.push_back(point{x, y});
}
// TODO: Do something with the points
}
-
使用
std::getline()
读取一条线 如下所述,将字符串拆分为白色空间
将每个元素推向向量。
重复下一行,直到文件结束
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入