繁体   English   中英

文件输入/输出C ++

[英]File input/output C++

我想读取以下文件:其中以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

我的想法是:

  1. 逐行读取,直到一行的第一个索引== 'p';
  2. 将矩阵初始化为节点大小,此处为50。
  3. 读取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的标头: #include<sstream>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM