Rolling total from sensors with sleeping arduino.

I'm using RocketScreams sleep library http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/ to put my arduino to sleep for 4 cycles of 2 seconds and then to take a reading from a sensor. It then prints out that reading to serial.

I am trying to get a rolling total by adding up all of the sensor readings but it's coming out in a strange format that I don't understand.

Here is the code:

 // **** INCLUDES *****
#include "LowPower.h"


const int pwPin1 = 3;

int sensorpower = 12; // counter per 8 seconds

int counter = 0;   // counter

long total = 0L;   // total

long cm2 =0L;

long average = 0L;   // counter

long sensor1, cm;

void setup () {
  Serial.begin(9600);
  pinMode(pwPin1, INPUT);
  pinMode(sensorpower, OUTPUT); 
}

void read_sensor(){
  sensor1 = pulseIn(pwPin1, HIGH);
  cm = sensor1/58;
}

void loop () {
  
  
      // Enter power down state for 2 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF);  
    
    // Do something here
      counter++;
      Serial.print(counter);
      Serial.print(",");
    
  if (counter == 4) {
    
  digitalWrite(sensorpower, HIGH);
  read_sensor();
  printall();
  delay(50);
  digitalWrite(sensorpower, LOW);
  total = total + cm;
   Serial.println();
    Serial.print("Total=");
    Serial.print(total);
    Serial.println();
    counter=0;
  }
  
  

delay(5);
}

void printall(){
  Serial.println();
  Serial.print("S1");
  Serial.print(" = ");
  Serial.print(cm);
  Serial.print("cm");

}

And here's what the serial looks like:

1,2,3,4,
S1 = 153cm
TotX«?ªþ3
1,2,3,4,
S1 = 32cm
TotX«?Âþ5
1,2,3,4,
S1 = 56cm
TotX«?¢þ1

If I replace

    LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF);

with

   delay(2000);

I get this which is exactly what I want to have so it suggests to me that it is something to do with the library

1,2,3,4,
S1 = 153cm
Total=153
1,2,3,4,
S1 = 153cm
Total=306
1,2,3,4,
S1 = 153cm
Total=459

I don't see anything that stops you from powering down before the serial transmission has completed. Wouldn't that corrupt the output, since the bitstream would halt and then be resumed when the chip is woken up again? Perhaps it would be better to call Serial.flush() before powering down. (I'm not sure whether flush() waits for the final byte to leave the UART, or only for the software buffer to be empty; you might need to add a timed delay to allow the final byte to be transmitted.)

Thank you very much, adding Serial.flush(); at the end of my loop has fixed it.