【问题标题】:C++ Ignore certain strings when reading fileC ++读取文件时忽略某些字符串
【发布时间】:2017-05-22 01:39:07
【问题描述】:

我目前正在尝试执行Clique Problem 并遇到了一个问题。我正在从文件中读取图表,但文件遵循特定格式:

c   File  p_hat1500-1.clq
c   
c
p edge  1500    284923  
e 4 1
e 5 3
e 5 4
e 6 2

在每一行之前是一个字母,指示该行上的内容(无论是注释 (c) 还是边缘 (e)),我试图找出如何读取文件并忽略所有元素从边缘编号,以便它改为这样读取:

4 1
5 3
5 4
6 2

到目前为止,我只是在阅读这样的文件:

ifstream file("graph.clq");

并加载

file >> n;

【问题讨论】:

  • “删除不必要的部分”是什么意思?您的意思是通过您正在编写的程序更改该文件吗?您的意思是只读取边缘的文件吗?
  • 我的意思是读取只有边缘的文件。

标签: c++ string file load


【解决方案1】:

试试这个

#include <vector>
#include <iostream>
#include <utility>
#include <fstream>
#include <string>

using std::cout;
using std::endl;
using std::cerr;
using std::vector;
using std::string;

vector<std::pair<int, int>> read_graph_file(const string& file);

int main() {

    auto edges = read_graph_file("input.txt");
    for (auto edge : edges) {
        cout << edge.first << " " << edge.second << endl;
    }

    return 0;
}


vector<std::pair<int, int>> read_graph_file(const string& file) {
    auto fin = std::ifstream{file.c_str()};
    if (!fin) {
        throw std::runtime_error{"Could not open file"};
    }

    auto edges = vector<std::pair<int, int>>{};

    auto input_type = char{};
    while (fin >> input_type) {
        if (input_type != 'e') {
            while (fin.get() != '\n') {}
        } else {
            auto edge = std::pair<int, int>{};
            fin >> edge.first >> edge.second;
            edges.push_back(edge);
        }
    }

    return edges;
}

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多