-1

所以我有一个关于图表的问题,我必须从输入文件中读取多个案例并检查适当性。每个案例在第一行都有 n,它具有的节点数,在第二行有一个整数序列 xy,其中 (x, y) 是一条边。问题是我不知道我有多少边缘,所以我不知道在哪里停止阅读。

例子:

输入文件 :

5

1 2 1 3 1 4 2 5 3 5 4 5

7

1 2 4 5 2 6

我在网上到处寻找解决方案,但找不到适合我的解决方案。我发现的大多数解决方案都只读取字符串。我试图找到并停在 '\n' 但那根本没有用。Int('\n') 在我的计算机上是 10,所以它与我的边缘序列中的 10 混淆了。它甚至没有读取'\ n'。

4

1 回答 1

0

这是一个解决方案:

struct Edge
{
  int x;
  int y;
  friend std::istream& operator>>(std::istream& input, Edge& e);
};

std::istream& operator>>(std::istream& input, Edge& e)
{
  input >> e.x;
  input >> e.y;
  return input;
}

这是一些主要代码:

int node_quantity = 0;
std::vector<Edge> database;
std::cin >> node_quantity;

// Ignore the newline following the number.
std::cin.ignore(1000, '\n');

// Start at the beginning of the line.
std::string text_line;
std::getline(std::cin, text_line);
// Read in the edges
std::istringstream text_stream(text_line);
Edge e;
while (text_stream >> e)
{
    database.push_back(e);
}

operator>>上面的代码创建了一个边缘结构和用于读取边缘的 重载。

第二个代码片段读入一行边缘并使用 astd::istringstream读取文本行中的所有边缘。

于 2020-02-24T20:24:03.433 回答