在C ++中解析格式化的用户输入 [英] Parsing formatted user input in C++
问题描述
对于一个项目,我需要实现图形着色问题的解决方案。但是,输入需要具有特定的语法,我不知道如何解析通过,以访问存储在变量中需要的数据。
For a project I need to implement a solution to the graph coloring problem. However, the input is required to have specific syntax with which I have no idea on how to parse through in order to access the data needed to store in variables.
输入约束是先输入颜色数,然后是顶点数,后跟一系列边。边应以(v1 v2)
的格式输入。序列以v1 = -1结束。因此,( - 1 0)
,( - 1 -1)
等。
The input constraints are to first enter the number of colors, then the number of vertices, followed by a sequence of edges. The edges should be entered in the format (v1 v2)
. The sequence is terminated with v1 = -1. So, (-1 0)
, (-1 -1)
, etc.
所以输入的结果是:
2 4 (0 1)(1 2)(2 3)(3 0)(-1 -1)
将非常感谢,因为我不知道哪里甚至开始!我知道这里有类似的问题,但我不知道如何应用他们的解决方案为这个具体的实现。
Any help would be greatly appreciated, as I have no idea where to even begin! I know there are similar questions here, however I can't figure out how to apply their solutions for this specific implementation.
推荐答案
尝试这样:
#include <iostream>
static inline int error(int n) { std::cerr << "Input error!\n"; return n; }
int main()
{
int nc, nv; // number of colours and vertices
if (!(std::cin >> nc >> nv)) { return error(1); }
for (int i = 0; i != nv; ++i)
{
char lb, rb;
int v1, v2;
if (!(std::cin >> lb >> v1 >> v2 >> rb) || lb != '(' || rb != ')') { return error(1); }
std::cout << "We have a pair [" << v1 << ", " << v2 << "]\n";
}
}
注意输入处理的关键原理:出现在条件上下文中。因为@jedwards说,输入可以是任何 std :: istream
,如字符串流或文件流,或在我的例子 std :: cin
。
Note the key principle of input processing: All input operations appear inside a conditional context. As @jedwards says, the input can be any std::istream
, such as a string stream or a file stream, or as in my example std::cin
.
这篇关于在C ++中解析格式化的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!