我想像这样格式化交流字符串printf
。例如:
char string[] = "Your Number:%i";
int number = 33;
// String should now be "Your Number:33"
有什么图书馆或我可以做到这一点的好方法吗?
我想像这样格式化交流字符串printf
。例如:
char string[] = "Your Number:%i";
int number = 33;
// String should now be "Your Number:33"
有什么图书馆或我可以做到这一点的好方法吗?
sprintf(char* out, const char* format, ... );
像这样使用:
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.
sprintf - http://linux.die.net/man/3/sprintf
为了调试我的 Arduino 草图,我习惯性地使用这个解决方案,取自Madivad对如何在字符串中打印多个变量的回答?.
您将此功能添加到您的草图中,这将允许您使用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);
}
}