我想格式化像printf
这样的c字符串。例如:
char string[] = "Your Number:%i";
int number = 33;
// String should now be "Your Number:33"
有没有图书馆或我能做到的好方法?
答案 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)
sprintf - http://linux.die.net/man/3/sprintf
答案 2 :(得分:0)
为了调试我的Arduino草图,我习惯性地使用这个解决方案,取自Madivad对How 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}}