14

I want to format a c string like printf does. For example:

char string[] = "Your Number:%i";
int number = 33;
// String should now be "Your Number:33"

Is there any library or a good way I could do this?

0

3 Answers 3

22

Use sprintf(char* out, const char* format, ... ); like so:

int main() {
  char str[] = "Your Number:%d";
  char str2[1000];
  int number = 33;
  sprintf(str2,str,number);
  printf("%s\n",str2);
  return 0;
}

Output:

---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
Your Number:33

> Terminated with exit code 0.
Sign up to request clarification or add additional context in comments.

3 Comments

What if you called sprintf() with a 1001 character long string? (answer: a nice segfault. Use snprintf() instead.)
Thank you, I already thought I remembered that there exists such an function but couldn't remember how it was called.
@H2C03 - Hmmm, I don't seem to have that function available with my compiler (MS Visual Studio 2008 C++). Good idea though, but I'm not sure it's available on all compilers.
1

sprintf - http://linux.die.net/man/3/sprintf

Comments

1

For debugging my Arduino sketches, I habitually use this solution, taken from Madivad's answer to How do I print multiple variables in a string?.

You add this function to your sketch, that will allow you to use printf(), although it falls over for float, %f.

// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

Add the global

FILE serial_stdout;

and put this is setup()

fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

An example sketch would be:

// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;


void setup(){
    Serial.begin(9600);

    // Set up stdout
    fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
    stdout = &serial_stdout;

    printf("My favorite number is %6d!\n", 12);
}

void loop() {
  static long counter = 0;
  if (millis()%300==0){
    printf("millis(): %ld\tcounter: %ld (%02X)\n", millis(), counter, counter++);
    delay(1);    
  }
}

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.