0

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:

  1. read line by line until the first index of a line == 'p';
  2. initialize my matrix to size of nodes, which would be 50 here.
  3. read 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++.

3
  • Start small: read the file line by line and print it out. Once that works, improve it by checking the first char in each line and ignoring comments. Then improve again, only print the info you need, etc. Commented May 26, 2018 at 16:10
  • This should get you started... cpppatterns.com/patterns/read-line-by-line.html Commented May 26, 2018 at 17:13
  • If you have no idea how to get started at all, you very likely won't really understand any solution we give you. Consider learning how to read a file line by line first, and then parsing each of the lines. Commented May 26, 2018 at 18:10

1 Answer 1

1

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>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.