skip to Main Content

I have a telegram that i have to send to the PLC, 1 substring of that telegram provides the barcodeID. It has 6 spaces and it starts with 1 and it is counting up.

For the PLC to work i have to fill up to empty spots wit an underscore. F.E.

_____1
____22
___333

Is there a way i can fix this?

I know that i can fill up the empty spaces with zero’s like this: %06d

000001
000022
000333

gLog.LogPrintf(Info, "customerlog", "Storage Out Ready: %02d%02d%02d%s%04d%010d%02d%010d%010d%06d%06d%06d%06d%06d%06d%010d",
        (*inMessage)["sender"].asInt(), (*inMessage)["reciever"].asInt(), (*inMessage)["series"].asInt(), (*inMessage)["type"].asString().c_str(),
        (*inMessage)["command"].asInt(), (*inMessage)["id"].asInt(), (*inMessage)["priority"].asInt(), (*inMessage)["source"].asInt(),
        (*inMessage)["target"].asInt(), (*inMessage)["height"].asInt(), (*inMessage)["width"].asInt(), (*inMessage)["length"].asInt(),
        (*inMessage)["weight"].asInt(), (*inMessage)["status"].asInt(), (*inMessage)["error"].asInt(), (*inMessage)["data"].asInt());
        gLog.LogPrintf(Info, "Barcode ID: ", (*inMessage)["id"].asCString());
        gLog.LogPrintf(Info, "error: ", (*inMessage)["error"].asInt());

2

Answers


  1. If you are able to use the standard library, you can use the formatting capabilities it provides. Here a mini demo of that:

    #include <iostream>
    #include <iomanip>
    #include <sstream>
    
    #define BUFFER_SIZE (10)
    int main() {
      std::stringstream buffer;
      buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1;
      std::cout << buffer.str() << std::endl;
      buffer.str(std::string());
      buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234;
      std::cout << buffer.str() << std::endl;
      buffer.str(std::string());
      buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234567;
      std::cout << buffer.str() << std::endl;
      buffer.str(std::string());
      return 0;
    }
    

    std::right makes the formatting to align to right, std::setfill sets ‘_’ as padding character and std::setw sets the width required.
    Best regards.

    Login or Signup to reply.
  2. If you have to go the C way, you can do it like this:

    #include <iostream>
    
    int main()
    {
      const char *padding = "______";
      int n = 123;
      char buf[7];
      int len;
      len = snprintf(buf, 7, "%d", n);
      printf("%.*s%s", 6 - std::min(6, len), padding, buf);
    }
    

    Output:

    ___123
    

    If the number has more than 6 digits, it will be truncated by taking only the 6 leftmost digits. For example, if n is 1234567890, the output will be 123456.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search