如何从文本文件中读取并将该数据添加到 C++ 中的图形中 [英] How to read from a text file and add that data to a graph in c++
问题描述
我有一个包含 256 对数据的文本文件.我需要将这些对放入图形的向量中.我知道如何在 C# 中做到这一点,但我是 C++ 的新手.文本文件的格式为
I have a text file that has 256 pairs of data. I need to take those pairs and put them into the vectors for the graph. I am know how to do this in C# but I am new to C++. The format of the text file is
125, 151
124, 176
ect...
我需要它以 graph[n][m] 的格式进入图形的向量,其中 n = 256 和 m = 256.所以我会通读文件,并在与 L/R 对对应的数字上标记 1.例如 125、151.我会转到第 125 行,并将第 151 行的 0 标记为 1.
I need it to come into the vectors for the graph in the format of graph[n][m], where n = 256 and m=256. So I would read through the file and would mark 1 on the number that corresponds with the L/R Pair. So for example 125, 151. I would go to the 125th line and I would mark the 151'st 0 to be 1.
[n][m]{{0,0,0... 1(//176th 0),0,0,0...}, //124th line
{0,0,0... 1(//151st 0),0,0,0...}, //125th line
ect.
C++ 有没有类似于 C# 中的 streamreader 方法?
Does C++ have anything like the streamreader method out of C#?
这是一个 7x7 最大流问题的向量示例.
Here is a sample of the vectors for a 7x7 max flow problem.
int graph[V][V] = { {0, 6, 7, 0, 0, 0, 0},
{0, 0, 1, 3, 4, 0, 0},
{0, 0, 0, 2, 0, 5, 0},
{0, 0, 0, 0, 3, 2, 0},
{0, 0, 0, 0, 0, 0, 7},
{0, 0, 0, 0, 2, 0, 4},
{0, 0, 0, 0, 0, 0, 0}
};
推荐答案
正如@Beta 在您的问题下的评论中所说,您想要
1)创建一个充满零的二维容器
2) 从文本文件中读取数字
3)根据数字改变容器中的一些元素.
as @Beta said in the comments under your question, you want to
1) create a 2-dimensional container full of zeroes
2) read numbers from a text file
3) change some of elements in the container according to the numbers.
这里有一些提示:
1- 用于创建 2D 容器:
So here some tips:
1- For creating a 2D container:
auto a = new int[100, 100]{0};
在这段代码中,您创建了一个充满零的 int
数组.未在 { }
部分初始化的元素将设置为默认值.int 为零.
in this code you made an array of int
s which is full of zeros. the elements that were not initialized in { }
part, would set to default value. which is zero for int.
2- 从文本文件中读取数字:
2- reading numbers from a text file:
#include <iostream>
#include <fstream>
并在您的代码中:
int x , y;
ifstream fin("yourFile.txt");
fin >> x >> y; //Jusy like "cin"
//Do what you want
//and after that close the stream
fin.close();
3- 根据数字改变容器中的一些元素:只需这样做:
3- change some of elements in the container according to the numbers: Simply do it like this:
a[i,i] = x;
这篇关于如何从文本文件中读取并将该数据添加到 C++ 中的图形中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!