C - Format char array like printf

試著忘記壹切 提交于 2019-12-21 05:13:11

问题


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?


回答1:


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.



回答2:


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




回答3:


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);    
  }
}


来源:https://stackoverflow.com/questions/10820377/c-format-char-array-like-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!