问题描述
我正在尝试在字符串旁边打印一个整数,但它并没有真正起作用,而且我很困惑.
I am trying to print an integer alongside a string but it's not really working out and am getting confused.
int cmdSeries = 3;
Serial.println("Series : " + cmdSeries);// That's where the problem occur
在visual basic中,我们曾经这样做过:
In visual basic we used to do it this way:
Dim cmdSeries As Integer
Console.Writeline(""Series : {0}", cmdSeries)
所以我用 Serial.println 尝试过,但它返回这个错误:调用重载 'println(const char [14], int&)' 不明确
So i've tried it with Serial.println but it returns this error :call of overloaded 'println(const char [14], int&)' is ambiguous
谁能帮助我,我想在不使用任何库的情况下以干净的方式实现这一目标.
Can anyone help my out, I want to achieve this without using any libraries and in a clean way.
推荐答案
Arduino String 类和常规 C 字符串之间存在巨大差异.第一个重载加法运算符,但几乎过度使用动态内存.主要是如果你使用类似的东西:
There is a huge difference between Arduino String class and regular C-string.The first one overloads addition operator, but there is almost excessive usage of dynamic memory. Mainly if you use something like:
String sth = String("blabla") + intVar + "something else" + floatVar;
更好的是使用:
Serial.print("Series : ");
Serial.println(cmdSeries);
顺便说一句,这个字符串文字驻留在闪存和 RAM 内存中,所以如果你想强制只使用闪存:
Btw, this string literal resides in Flash and RAM memory, so if you want to force using flash only:
Serial.print(F("Series : "));
但它仅适用于基于 AVR
的 Arduinos.如果您使用大量文字,此宏可以节省大量 RAM.
But it's for AVR
based Arduinos only. This macro can save a lots of RAM, if you are using lots of literals.
有时我用这个:
template <class T> inline Print & operator<<(Print & p, const T & val) {
p.print(val);
return p;
}
// ...
Serial << F("Text ") << intVar << F("...") << "\n";
它单独打印每个部分,没有串联.
It prints each part separately, no concatenations or so.
这篇关于如何在字符串 Arduino 旁边打印整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!