文件输入/输出C ++

时间:2018-05-26 16:07:09

标签: c++ file-io

我想读取以下文件:以c开头的行代表注释,p代表图形信息(没有节点,没有边缘),e代表边缘。

$(document).ready(function(){
            $(".showcontent").click(function () {
         var name = $(this).attr('id');
          $("#content" + name).fadeIn(1000);
            });    
                 $(".content h3").click(function () {
           var sub = $(this).attr('id');
          $("#X" + sub).slideDown(500);
            });

});

我对这是如何工作的想法是:

  1. 逐行读取,直到行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
  2. 的第一个索引
  3. 将我的矩阵初始化为节点大小,此处为50。
  4. 阅读== 'p'; - 行数,将它们保存到我的数据结构中(在示例中为654行)。
  5. 我知道如何在Python中完成这项工作,但是我不知道从哪里开始使用c ++。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样做:

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.

请务必添加标头以使用字符串流:#include<sstream>