9

I have a string-mask that looks something like this:

                  +--\
                  |   \
                  |    \
              +---|     \
              +---|      \
+                 |       \
|\  +---------------------------------+\
| \ | %d|    %d|    %d|    %d|    %d| | \
|  \| %d|    %d|    %d|    %d|    %d| | |\
|   | %d|    %d|    %d|    %d|    %d| | | \
|---|                                 | |  \
|---|                                 | |  /
|   | %d|    %d|    %d|    %d|    %d| | | /
|  /| %d|    %d|    %d|    %d|    %d| | |/
| / | %d|    %d|    %d|    %d|    %d| | /
|/  +---------------------------------+/
+                 |       /
              +---|      /
              +---|     /
                  |    /
                  |   /
                  +--/

I need to printf it - printf(string-mask, param1,param2,param3, etc...), but number of parameters is a huge (in real string it is about 40). Is there way to avoiding manual enumeration of parameters?

P.S. I'm using pure C.

P.S.S. params are storing in array.

12
  • "manual enumeration"? Can you define that?, you're probably not going to escape loops. Commented Jun 2, 2016 at 21:10
  • @self printf(string-mask, param1,param2,param3, etc...) is a manual enumeration. Commented Jun 2, 2016 at 21:12
  • 2
    Using a loop is not mutually exclusive with printing it once. Commented Jun 2, 2016 at 21:20
  • 2
    Would you like the compiler to guess the parameters for you, so you don't have to enumerate them? ;-) Commented Jun 2, 2016 at 21:21
  • 2
    Probably doable with some variadic arg hackery. Good luck. Commented Jun 2, 2016 at 21:39

1 Answer 1

5

Iterate the array (the string), until you hit a print specifier. Then print the string from where you previously left of, to, including, the specifier, while passing a single argument from the array of values.

This is a quick and dirty solution without error checking that assumes every specifier is exactly %d and there are exactly param_count of them. Also the string must be modifiable.

const size_t param_count = 30;
char* first = string;
char* last = string;
for( size_t i = 0 ; i < param_count ; i++ )
{
    last = strchr( last , '%' ); //find the specifier 
    last += 2 ;  //skip the specifier
    const char temp = *last;
    *last = '\0';  //terminate the 'sub-string'
    printf( first , param[i] );
    *last = temp;   //restore the 'string'
    first = last;
}
printf( first ); //print the remaining string

Here is the output: https://ideone.com/zIBsNj

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.