问题
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.
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.
So the input will end up looking something along the lines of:
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.
回答1:
Try something like this:
#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";
}
}
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
.
回答2:
You might want to look into the standard input/output. Basically, ask for the user to enter the input, and get it like this: std::string mystr; std::getline(con, mystr);
and then parse it using the >>
operator and std::stringstream
. You can skip spaces or parenthesis by just storing it in a char. So, to get the first two numbers, do: int colors, verts; char c; stringstream(mystr) >> colors >> c >> verts;
You can then expand this for the rest of your input.
来源:https://stackoverflow.com/questions/10466984/parsing-formatted-user-input-in-c