I am wanting to read a file of the following: Where lines starting with c stand for comments, p stands for graph information (no of nodes, no of edges) and e stands for edges.
c //Comments
c //Comments
c //Comments
p edge 50 654
e 4 1
e 5 3
e 5 4
e 6 2
e 6 3
... // 654 edges
My idea of how this would work is:
== 'p';
amount_of_edges
-number of lines, saving them into my data structure (which would be 654 lines in the example). I know how I could do this simply in Python, however I just don't know where to get started with c++.
You can try to do it like this:
ifstream file("myfile.txt");
string line;
while(true){
getline(file, line);
if(line[0]=='p') break;
}
//now line contains a line starting with 'p' which contains the numbers
//that you need
stringstream data_from_line_with_p;
data_from_line_with_p << line;
//we have send the line to a stream, from which we can read to the variables
string p, edges;
int size_of_nodes, amount_of_edges;
//let's now assign these variables with data from the stream:
data_from_line_with_p >> p >> edges >> size_of_nodes >> amount_of_edges;
//now size_of_nodes and _amount_of_edges store the values read from this
//line and you can use them to build the structure that you want
//You also store here the word after 'p' in the variable 'edge' and you
//can use it also if you need.
Remember to add a header for using stringstreams: #include<sstream>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.