【问题标题】:the characters in a c++ string are being ignoredc++ 字符串中的字符被忽略
【发布时间】:2020-07-06 23:13:09
【问题描述】:

我正在尝试使用 signal11 的 hidapi (here) 写入隐藏设备。 在我的故障排除中,我注意到字符串的一部分没有显示在控制台上。 这是我的代码示例

//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";
}

我希望控制台返回以下内容:

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

但是,这种情况发生了:

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

缺少“写成功”、结果和换行符,我对 c++ 有点陌生,但我有使用 c# 的经验。我很困惑,非常感谢您的帮助,提前感谢您是否需要更多信息!

【问题讨论】:

    标签: c++ string char hidapi


    【解决方案1】:

    这一行:

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

    将打印字符串"Write success: ",偏移量为10个字符,即\n的ascii值。因此您会在屏幕上看到ess

    你可能想要:

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

    假设res 根据需要返回0-1

    【讨论】:

      【解决方案2】:

      不要将字符“添加”到字符串中。它不会像你期望的那样。

      在这里,您认为您正在将换行符添加到字符串“写入成功”中,而实际上您是在告诉编译器获取常量字符串并且仅从第 10 个字符开始流式传输。请记住,这里的常量字符串只是一个字符数组,单个字符 '\n' 被转换为数字 10。

      您也错过了流式传输的结果。

      所以你的倒数第二行应该是:

      std::cout << "Write success: " << res <<  std::endl;
      

      【讨论】:

      • 我在搞砸 res 变量时实际上忘记输出它,但感谢您的回答,它帮助很大!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多