Read texts using sscanf

2019-09-16 20:12发布

问题:

I have a question regarding to usage of sscanf function.

#include  <iostream>
#include  <stdio.h>

int main()
{
    char a[3];
    char b[4];
    const char* p = "aaaaaaaaaaaaaaaaaa bbbbbb";
    sscanf(p, "%2s %3s", a, b);
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    return 0;
}

The desired output would be: aa bbb

Actual output is: aa aaa

回答1:

If you would like to skip all characters up to a space, use %*[^ ]:

sscanf(p, "%2s%*[^ ] %3s", a, b);

The asterisk after % tells sscanf to ignore the corresponding portion of the input.

This produces the desired output (demo 1).

why this case is not working?

char a[5];
char b[6];
const char* p = "word word2 , word";
sscanf(p, "%4s%*[^ ] %5s", a, b);

This does not work because %s and %[...] do not mix very well. Replace %Ns with %N[^ ]:

sscanf(p, "%4[^ ]%*[ ]%5[^ ]", a, b);

demo 2.



标签: c++ c scanf