I want to have a line like this
Serial.println(count*"B");
So if count=6
, it would print BBBBBB
, etc.
Is there anything like this for arduino?
3 Answers 3
A more simple "noob" way could also be:
int count = 6
for(int i=0; i<count; i++)
{
Serial.print("b");
}
Serial.println();
-
This is what I ended up doing (although made the for loop one line). I wasn't really looking to make my own method like the others have done, I was just hoping there'd be some kind of
string * int
syntaxMirror318– Mirror3182016年10月12日 01:08:28 +00:00Commented Oct 12, 2016 at 1:08
You can write a helper function to do it, like this:
void printRepeat (Stream & device, const char * str, unsigned int count)
{
while (count-- > 0)
device.print (str);
} // end of printRepeat
void setup()
{
Serial.begin (115200);
printRepeat (Serial, "-", 20);
Serial.println ();
} // end of setup
void loop()
{
printRepeat (Serial, "Hello, World! ", 5);
Serial.println ();
delay (500);
} // end of loop
The function printRepeat
is passed a Stream
argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.
Just for fun, here is a version of Nick Gammon's answer reformulated with some C++ magic:
// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
RepeatedString(const char * str, unsigned int count)
: _str(str), _count(count) {}
size_t printTo(Print& p) const
{
size_t sz = 0;
for (unsigned int i = 0; i < _count; i++)
sz += p.print(_str);
return sz;
}
private:
const char * _str;
unsigned int _count;
};
void setup()
{
Serial.begin(115200);
Serial.println(RepeatedString("-", 20));
}
void loop()
{
Serial.println(RepeatedString("Hello, World! ", 5));
delay(500);
}
You can .print()
and .println()
the RepeatedString
s on anything
that can print.
-
1Nice! You can also overload "*" so that OP's exact syntax would work!xyz– xyz2016年10月11日 14:26:47 +00:00Commented Oct 11, 2016 at 14:26
count
has a reasonable limit.