c++ - 文件输入/输出 C++

标签 c++ file-io

我想读取以下内容的文件:其中以 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添加一个header:#include<sstream> .

关于c++ - 文件输入/输出 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544653/

相关文章:

c++ - QT - mousePressEvent 在双击时调用 3 次

java - 将文本文件的 X 和 Y 坐标读取到数组列表中

android - 在 Android 中获取选定的图像文件位置

c++ - 使用 cin 处理空白并返回(换行符)

c++ - 在 C++ 中计算尖点的斜率

java - Google Dataflow批处理文件处理性能不佳

c++ - 解析文件时输出错误?

java - 我该如何修复 Java 7 Files.write 错误?

c++ - 使用相同的 boost :thread variable to create multiple threads

具有混合虚拟和非虚拟基础的 C++11 类格?