This is a small test sketch :
I only want to print these lines if they contain anything:
Would anyone please assist me. Many thanks in advance.
char line0 [19];
char line1 [19];
char line2 [19];
char line3 [19];
void setup() {
Serial.begin(9600);
while (!Serial); // wait for serial connection
Serial.println("Starting... ");
sprintf(line0, "this line is not blank");
}
void loop() {
// I only want to print these lines if they are not blank
Serial.println(line0);
Serial.println(line1);
Serial.println(line2);
Serial.println(line3);
}
Global variables are initialised with zeroes So they don't contain anything.
Yes, it does work. Your problem is that you are overflowing your line0 with the sprintf so you're writing to memory that is not yours and after that all bets are off. Your lineX can only contain 18 characters taking into account that a c-string is terminated with a '\0'; count the number of characters that you're trying to put in line0.
sprintf assumes the buffer you provide is large enough to hold all of your output. If your buffer isn't large enough you get undefined results (probably by writing over other variables).
snprintf won't write characters beyond the number of characters you say are available in the buffer. You won't get all of your output if the buffer isn't large enough but at least you won't be writing on other variables.
strlen counts bytes until it stumbles on terminating 0. but you don’t need length you need to know if string is empty, that would mean that terminating 0 is the 1st byte. to make absolutely sure it is the 1st byte in newly created array, create it like this
I took that to mean "empty or only containing space characters" which I extended to mean "empty or only containing whitespace characters: space, tab, newline, or return". (I think that is what "isblank()" tests for)