简体   繁体   中英

C using scanf() for | delimited string

I want to input a few strings then two integers. Whilst the strings are separated by '|', the integers are kept apart by a '.'.

Looking around online I have seen some sort of syntax which involves [^] . I am using this but it is not working at all. Can someone please point out what I should be doing and why what I am doing is wrong?

sscanf(str, "%s[^|],%s[^|],%s[^|],%i[^|],%i[^.]", …);

The syntax is arcane at best — I'd suggest using a different approach such as strtok() , or parsing with string handling functions strchr() etc.

However the first thing you must realise is that the %[^<delimiter-list>] format specifier (a 'scan set' in the jargon, documented by POSIX scanf() amongst many other places) only extracts string fields — you have to convert the extracted strings to integer if that is what they represent.

Secondly you still have to include the delimiter as a literal match character outside of the format specifier — you have separated the format specifiers with commas where | are in the input stream.

Consider the following:

#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 ;
}

You must use either [] or s construct, but not both and your format string must incluse the separators.

So you should write something like :

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

This seems to work...

#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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM