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