C - 格式化char数组,如printf

时间:2012-05-30 16:27:34

标签: c string-formatting

我想格式化像printf这样的c字符串。例如:

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

有没有图书馆或我能做到的好方法?

3 个答案:

答案 0 :(得分:12)

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

输出:

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

> Terminated with exit code 0.

答案 1 :(得分:2)

答案 2 :(得分:0)

为了调试我的Arduino草图,我习惯性地使用这个解决方案,取自MadivadHow do I print multiple variables in a string?的回答。

您可以将此功能添加到草图中,这样您就可以printf()使用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; }

FILE serial_stdout;

添加全局

setup()

并将其设为fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE); stdout = &serial_stdout;

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

示例草图将是:

{{1}}