there is a function

#include <stdio.h> /* printf */ #include <stdarg.h> /* va_list, va_start, va_arg, va_end */ void format (int n, ...) { int i; double val; printf ("Printing floats:"); va_list vl; va_start(vl,n); for (i=0;i<n;i++) { val=va_arg(vl,double); printf (" [%.2f]",val); } va_end(vl); printf ("\n"); } int main () { PrintFloats (3,3.14159,2.71828,1.41421); return 0; } 

1 question, I can’t do it so that it considers the arguments itself and displays all the arguments 2 question how to make me ask the message format itself? Well, so I called the function like this format ("select * from where kod_tovara =% 1 and imya =% 2") please tell me

    1 answer 1

    she considered the arguments herself

    What is meant? If it’s about getting rid of the n parameter, then either you pass the number of arguments explicitly, or you use some sort of end of argument list:

     PrintFloats( 3.0, 3.14159, 2.71828, 1.41421, 0.0 ); // 0.0 (или любое другое заранее оговоренное // значение, например, -1970.0) - конец, больше аргументов не будет 

    so that I call a function like this format ("select * from where kod_tovara =% 1 and imya =% 2")

    So do:

     void format (const char * format, ...) { 

    Examples of implementation - in absolutely any Google Index from the very first links on request of the type "va_arg examples" dozens sprinkle. See, try. Even in man va_arg there are examples. In this case, the list of arguments will be taken from the format string, and there is no need to specifically transmit their number or end sign.

    For example, a slightly reworked example from man va_arg :

     #include <stdio.h> #include <stdarg.h> static void format( const char * fmt, ... ) { union { double f; int d; char * s; } var; va_list ap; va_start( ap, fmt ); while( *fmt ) { if( *fmt == '%' ) { fmt++; if( *fmt ) { switch( *fmt ) { case 'f': var.f = va_arg( ap, double ); printf( "%f", var.f ); break; case 's': var.s = va_arg( ap, char * ); printf( "%s", var.s ); break; case 'd': var.d = va_arg( ap, int ); printf( "%d", var.d ); break; default: printf( "%c", *fmt ); break; } } } else { printf( "%c", *fmt ); } fmt++; } va_end( ap ); } int main() { format( "int: %d, double: %f, string: %s\n", (int)1, (double)2, "3" ); return 0; } 

    PS I hope you do not seriously invent your bike to work with the database? If so, give up this idea soon and find normal ready-made libraries.

    • But could you give an example of how you can implement format ("select * from where kod_tovara =% 1 and imya =% 2", kod_tovara, imya); I'm really either drowning or skipping past my eyes - Mblp
    • man va_arg type, there is a section "EXAMPLE" :-) OK, I will rewrite in their own way an example from there. But if the manov example is not clear, ask specific questions. - dunduk