Advertisements
I have this simple test code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int a, b;
int ret = scanf("( %d , %d )", &a, &b);
if (ret != 2 ){
printf("Wrong input!\n");
return EXIT_FAILURE;
}
printf("Everything fine\n");
return EXIT_SUCCESS;
}
As you can see, the main function expects input for example (10, 15)
. This input (10, 15test
fails. But this input (10, 15]
is OK. Why? How can I force scanf to distiguish between types of brackets?
>Solution :
Note there’s no need for a space before %d — all numeric scanf specifiers, and also %s but not %c and %[…], skip any leading whitespace the same as space. Spaces are needed before the comma and the %1[)] if you want to allow whitespace there, which your example data doesn’t show.
int a,b; char c[2 /* or more */];
int ret = scanf("(%d ,%d %1[)]", &a,&b,c);
if( ret == 3 ) // all good