C using scanf() for | delimited string

后端 未结 3 845
小蘑菇
小蘑菇 2021-01-26 12:04

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

3条回答
  •  礼貌的吻别
    2021-01-26 12:22

    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 %[^] 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 
    
    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 ;
    }
    

提交回复
热议问题