Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scanf does not distinguis between brackets

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading