带有"_"分隔符的sscanf

Kit*_*cha 6 c

我在C中运行以下代码.我没有得到正确的答案.

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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是

Temp 1 is This
Temp 2 is 
Temp 3 is 
Temp 4 is 
Temp 5 is 
Run Code Online (Sandbox Code Playgroud)

我要做的是在个别变量上取"This""Is""A""Test"和"99".

ken*_*ytm 13

sscanf(test,"%[^'_'],%[^'_'],%[^'_'],%[^'_'],%s",tmp1,tmp2,tmp3,tmp4,tmp5);
Run Code Online (Sandbox Code Playgroud)

应该

sscanf(test,"%[^_]_%[^_]_%[^_]_%[^_]_%s",tmp1,tmp2,tmp3,tmp4,tmp5);
Run Code Online (Sandbox Code Playgroud)

请注意,您要使用,而不是分隔占位符_.

请参见http://ideone.com/8zBmG.

此外,'除非您想跳过单引号,否则您不需要s.

(顺便说一句,你应该看看strtok_r.)

  • @cnicutar:[No](http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html). (2认同)

thi*_*ton 5

您正在扫描字符串之间的逗号,文本中没有.从模式中删除它们:

sscanf(test,"%[^'_']%[^'_']%[^'_']%[^'_']%s",tmp1,tmp2,tmp3,tmp4,tmp5);
Run Code Online (Sandbox Code Playgroud)

撇号也许是不必要的.你不需要引用任何东西,因为没有shell会扩展它:

sscanf(test,"%[^_]%[^_]%[^_]%[^_]%s",tmp1,tmp2,tmp3,tmp4,tmp5);
Run Code Online (Sandbox Code Playgroud)

接受pmg的建议,你应该将你的临时长度显式地写入scanf参数,以确保你没有得到缓冲区溢出:

sscanf(test,"%9[^_]%9[^_]%9[^_]%9[^_]%9s",tmp1,tmp2,tmp3,tmp4,tmp5);
Run Code Online (Sandbox Code Playgroud)

然后检查返回值:

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); }
Run Code Online (Sandbox Code Playgroud)