Avinash
Avinash

Reputation: 13257

sscanf formatted input in C++

I have the following code which works if there are no spaces in the input string.

char* input2 = "(1,2,3)";
sscanf (input2,"(%d,%d,%d)", &r, &n, &p);

This fails for the following input:

char input2 = " ( 1 , 2 , 3  ) ";

How to fix this?

Upvotes: 3

Views: 239

Answers (1)

hochl
hochl

Reputation: 12920

Simple fix: add spaces in the pattern.

char* input2 = "( 1 , 2 , 3 )";
sscanf (input2,"( %d, %d, %d )", &r, &n, &p);

The spaces in the pattern consume any amount of whitespace, so you're fine. Test program:

        const char* pat="( %d , %d , %d )";
        int a, b, c;

        std::cout << sscanf("(1,2,3)", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("( 1 , 2 , 3 )", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("(1, 2 ,3)", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("(  1 , 2 ,   3 )", pat, &a, &b, &c) << std::endl;

Output:

3
3
3
3

This behaviour is because of the following paragraph from the manual:

A directive is one of the following:

·      A sequence of white-space characters (space, tab, newline, etc.;
       see isspace(3)). This directive matches any amount of white space,
       including none, in the input.

Upvotes: 3

Related Questions