user3475815
user3475815

Reputation: 11

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[^.]", …);

Upvotes: 1

Views: 2184

Answers (3)

Clifford
Clifford

Reputation: 93534

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

Upvotes: 4

Serge Ballesta
Serge Ballesta

Reputation: 149075

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, "%[^|]|%[^|]|...",...) 

Upvotes: 1

Jiminion
Jiminion

Reputation: 5164

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

}

Upvotes: 1

Related Questions