我想读取以下内容的文件:其中以 c 开头的行代表注释,p 代表图形信息(节点数,边数),e 代表边。
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
我的想法是:
- 逐行读取直到一行的第一个索引
== 'p';
- 将我的矩阵初始化为节点大小,此处为 50。
- 读取
amount_of_edges
- 行数,将它们保存到我的数据结构中(在示例中为 654 行)。
我知道如何在 Python 中简单地做到这一点,但我只是不知道从哪里开始使用 C++。
最佳答案
你可以尝试这样做:
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.
记得为使用stringstreams添加一个header:#include<sstream>
.
关于c++ - 文件输入/输出 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544653/