1

How should I make a variable format sequence for sprintf?.

int i=2,d=9;
String sf;
sprintf(sf,"%%0%d",i);
fprintf(sf,d); 

While expecting the output.

09

The compilation fails, with several errors, according the failing change I apply.

Invalid cast from type 'String' to type 'char*'
asked Apr 30, 2019 at 5:33
2
  • 2
    this may help ..... majenko.co.uk/blog/evils-arduino-strings Commented Apr 30, 2019 at 6:04
  • 1
    Hint: Try char sf[32]; and then correct the rest. Commented Apr 30, 2019 at 6:07

1 Answer 1

3
  1. sprintf cannot be used to write data into String objects. More precisely, it is possible to come up with a "hackish" way to write the result directly into a String object, but the latter is definitely not designed for such use.

    The target buffer should be an array of char, not a String. Which is what the compiler is telling you.

    char buffer[64];
    sprintf(buffer, "%%0%d", i);
    

    or better

    char buffer[64];
    snprintf(buffer, sizeof buffer, "%%0%d", i);
    
  2. The format string you used in your sprintf will generate %02 result (since i contains 2 at that moment). Why you are expecting 09 is not clear. Why are you expecting the % character to disappear is not clear either, considering that the format string seems to be deliberately designed to include it.

  3. A String object cannot be used as the first parameter of fprintf. It is not clear what that fprintf is doing in your code.

Apparently you are trying to use sprintf to generate another format string at run time (using i as field width), which is later used to output the d variable. In that case that would be something like

char format[16];
snprintf(format, sizeof format, "%%0%dd", i);
fprintf(file, format, d);

That fprintf will indeed output 09.

answered Apr 30, 2019 at 13:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.