Home > Article > Backend Development > How can I read graph adjacency information from a text file and store it into a vector in C ?
Reading Graph Adjacency Information from a Text File in C
To read graph adjacency information from a text file and store it into a vector, where each line contains a variable number of integers, we can employ the following steps:
Firstly, we include necessary headers for file manipulation and string streams:
<code class="cpp">#include <fstream> #include <sstream></code>
Next, we open the text file using an ifstream object:
<code class="cpp">std::ifstream infile("thefile.txt");</code>
We establish a string to store each line:
<code class="cpp">std::string line;</code>
Then, we enter a loop to read each line one by one:
<code class="cpp">while (std::getline(infile, line))</code>
For each line, we create an istringstream to process the string:
<code class="cpp">std::istringstream iss(line);</code>
We declare an integer n and a vector v to store the parsed integers:
<code class="cpp">int n; std::vector<int> v;</code>
Inside another while loop, we iterate over the istringstream, reading integers into n and pushing them into the vector:
<code class="cpp">while (iss >> n) { v.push_back(n); }</code>
Finally, we can use the v vector to represent the adjacency information.
The above is the detailed content of How can I read graph adjacency information from a text file and store it into a vector in C ?. For more information, please follow other related articles on the PHP Chinese website!