Sscanf delimited by "_" in C

I am running the following code in C. I am not getting the correct answer.

int main()
{

    char test[100] = "This_Is_A_Test_99";
    char tmp1[10],tmp2[10],tmp3[10],tmp4[10],tmp5[10];

    sscanf(test,"%[^'_'],%[^'_'],%[^'_'],%[^'_'],%s",tmp1,tmp2,tmp3,tmp4,tmp5);

    printf ("Temp 1 is %s\n",tmp1);
    printf ("Temp 2 is %s\n",tmp2);
    printf ("Temp 3 is %s\n",tmp3);
    printf ("Temp 4 is %s\n",tmp4);
    printf ("Temp 5 is %s\n",tmp5);

    return 0;
}

The output I get is

Temp 1 is This
Temp 2 is 
Temp 3 is 
Temp 4 is 
Temp 5 is 

What I need to do is fetch "This" "Is" "Test" and "99" for individual variables.

+5
source share
3 answers
sscanf(test,"%[^'_'],%[^'_'],%[^'_'],%[^'_'],%s",tmp1,tmp2,tmp3,tmp4,tmp5);

it should be

sscanf(test,"%[^_]_%[^_]_%[^_]_%[^_]_%s",tmp1,tmp2,tmp3,tmp4,tmp5);

Note that you are separating placeholders ,instead _.

See http://ideone.com/8zBmG .

Also, you do not need 'it if you do not want to skip single quotes.

(By the way, you should look in strtok_r.)

+11
source

You scan commas between your lines, and they are not in the text. Remove them from the template:

sscanf(test,"%[^'_']%[^'_']%[^'_']%[^'_']%s",tmp1,tmp2,tmp3,tmp4,tmp5);

, , . , :

sscanf(test,"%[^_]%[^_]%[^_]%[^_]%s",tmp1,tmp2,tmp3,tmp4,tmp5);

pmg, scanf, , :

sscanf(test,"%9[^_]%9[^_]%9[^_]%9[^_]%9s",tmp1,tmp2,tmp3,tmp4,tmp5);

:

int token_count = sscanf(test,"%9[^_]%9[^_]%9[^_]%9[^_]%9s",tmp1,tmp2,tmp3,tmp4,tmp5);
if ( token_count != 5 ) { fprintf(stderr, "Something went wrong\n"); exit(42); }
+4

, (,) sscanf.

. - sscanf "This"

:

"%[^_]_%[^_]_%[^_]_%[^_]_%s"
+2

All Articles