Search code examples
c++stringcharhidapi

the characters in a c++ string are being ignored


I'm trying to write to a hid device using signal11's hidapi (here). In my troubleshooting, I've noticed that part of a string isn't being displayed to the console. Here is a sample of my code

//device is a hid device and is assigned to in another part of the program.
//dataBuffer is a struct with only a char array called "buffer" and an int which is the size of the array called "size"
void DeviceCommands::Write(hid_device* device, dataBuffer* buf)
{
    std::cout << "Attempting write >> buffer...\n";
    buf->buffer[0] = 0;
    std::cout << "Written to buffer...\n" << "writing buffer to device\n";
    int res = hid_write(device, buf->buffer, sizeof(buf->buffer));
    std::cout << "Write success: "  + '\n';
    std::cout << "Write complete\n";
}

I'm expecting for the console to return the following:

Attempting write >> buffer...
Written to buffer...
writing buffer to device
Write success: (0 if the write succeeds, -1 if it fails)
Write complete

But instead, this happens:

Attempting write >> buffer...
Written to buffer...
writing buffer to device
ess: Write complete

The "Write succ", result, and the line break are missing, I'm somewhat new to c++ but I have experience with c#. I'm just confused and some help would be much appreciated, thanks in advance and ask if you need more information!


Solution

  • This line:

    std::cout << "Write success: "  + '\n';
    

    will print the string "Write success: " with an offset of 10 characters, which is the ascii value of \n. Hence you see ess on the screen.

    You probably want:

    std::cout << "Write success: " << res << "\n";
    

    assuming res returns 0 or -1 as needed.