Read specific pattern in C from standard in
I am having trouble reading some standard input on a console application in C.
I need to get the input in a specific pattern/format such as '(num, num)' without the quotes. That being [[ open parenthesys, a number, a comma, a space, another number, closing parenthesys ]].
When I had my program read with scanf("%d %d", &a, &b);
it would read two numbers separated by a space. I want to try and make it understand the desired pattern as described above such as scanf("(%d, %d)", &a, &b);
where a is the first number and b is the second. This does not work as after this scanf, I also have another input prompt which gets skipped due to the string pattern but works with scanf("%d %d", &a, &b);
. Any advice?
int main(int argc, char* argv[]) {
int a, b, c;
printf("This is where the pait is required: ");
scanf("(%d, %d)", &a, &b);
printf("a: %d, b: %d\n", a, b); // Check values here...
printf("This is where I ask for another number as input: ");
scanf("%d", &c);
printf("c: %d\n", c); // Check value here...
// Do stuff here but above code should skip over the second scanf...
exit(0);
}
Solution 1:
As stated by @dxiv
"It's safer to just use " (%d ,%d )"
in both places, with no getchar needed"
"Also note that %d 'absorbs' any leading whitespace, so the format would read (123,456)
with any number of spaces or newlines inserted between the numbers and delimiters."