C对|分隔字符串使用scanf()

C对|分隔字符串使用scanf(),c,C,我想输入几个字符串,然后输入两个整数。字符串之间用“|”分隔,整数之间用“.”分隔 在网上四处看看,我看到了一些涉及[^]的语法。我正在使用这个,但它根本不起作用。有人能指出我应该做什么,为什么我做的是错的吗 sscanf(str, "%s[^|],%s[^|],%s[^|],%i[^|],%i[^.]", …); 这似乎有效 #include <stdio.h> main() { char x[32] = "abc|def|123.456."; char y[20]; cha

我想输入几个字符串,然后输入两个整数。字符串之间用“|”分隔,整数之间用“.”分隔

在网上四处看看,我看到了一些涉及
[^]
的语法。我正在使用这个,但它根本不起作用。有人能指出我应该做什么,为什么我做的是错的吗

sscanf(str, "%s[^|],%s[^|],%s[^|],%i[^|],%i[^.]", …);
这似乎有效

#include <stdio.h>

main()
{

char x[32] = "abc|def|123.456.";
char y[20];
char z[20];
int i =0;
int j =0;
sscanf(x,"%[^|]|%[^|]|%d.%d.",y,z,&i,&j);
fprintf(stdout,"1:%s 2:%s 3:%d 4:%d\n",y,z,i,j);

}
#包括
main()
{
字符x[32]=“abc | def | 123.456.”;
chary[20];
charz[20];
int i=0;
int j=0;
sscanf(x,“%[^ |]%[^ |][d.%d.”,y,z,&i,&j);
fprintf(标准符号,“1:%s2:%s3:%d4:%d\n”,y,z,i,j);
}

必须使用
[]
s
构造,但不能同时使用格式字符串必须包含分隔符

所以你应该写一些类似的东西:

sscanf(str, "%[^|]|%[^|]|...",...) 

语法充其量是晦涩难懂的——我建议使用不同的方法,例如
strtok()
,或者使用字符串处理函数
strchr()
进行解析

然而,您必须意识到的第一件事是,
%[^]
格式说明符(术语中的“扫描集”,由POSIX记录) 在许多其他地方)只提取字符串字段-如果提取的字符串表示整数,则必须将其转换为整数

其次,您仍然必须将分隔符作为文本匹配字符包含在格式说明符之外-您已经用逗号分隔了格式说明符,其中输入流中有

考虑以下几点:

#include <stdio.h>

int main()
{
    char a[32] ;
    char b[32] ;
    char c[32] ;
    char istr[32] ;  // Buffer for string representation of i
    int i ;
    int j ;          // j can be converted directly as it is at the end.

    // Example string
    char str[] = "fieldA|fieldB|fieldC|15.27" ;

    int converted = sscanf( str, "%[^|]|%[^|]|%[^|]|%[^.].%i", a, b, c, istr, &j ) ;

    // Check istr[] has a field before converting
    if( converted == 5 )
    {
        sscanf( istr, "%i", &i) ;
        printf( "%s, %s %s, %d, %d\n", a, b, c, i, j ) ;
    }
    else
    {
        printf( "Fail -  %d fields converted\n", converted ) ;
    }

    return 0 ;
}
#包括
int main()
{
chara[32];
charb[32];
charc[32];
char istr[32];//用于i的字符串表示的缓冲区
int i;
int j;//j可以直接转换为结尾处的值。
//示例字符串
char str[]=“fieldA | fieldB | fieldC | 15.27”;
int converted=sscanf(str,“%[^ |][124;%[^ |][124;]%[^ |][124^.%[^.].%i”、a、b、c、istr和j);
//转换前检查istr[]是否有字段
如果(转换==5)
{
sscanf(istr、%i、&i);
printf(“%s,%s%s,%d,%d\n”,a,b,c,i,j);
}
其他的
{
printf(“转换失败-%d个字段\n”,已转换);
}
返回0;
}

对于初学者,请尝试
%[^ |]|
s
毫无意义。与其只描述输入格式,不如添加一个示例?还有“在线环顾四周”-发布链接!。更完整的代码也会有帮助-这是一个不完整的声明。也许
sscanf(str,“%[^ |]]%[^ |]]%[^ |][i.%i
这群人中最好的答案。糟糕的是,40多天来的OP都没有接受答案。