为什么参数接受 "text" 而不是字符串变量?
Why argument accept "text" but not string variable?
我正在尝试将来自 microbit 加速度计的整数 x y z 组合成一个字符串,然后将其发送到串口。我在这里使用在线 mbed 编译器中的 c++ 和 microbit DAL 库。
uBit.init();
uBit.serial.baud(115200);
MicroBitI2C i2c = MicroBitI2C(I2C_SDA0, I2C_SCL0);
MicroBitAccelerometer accelerometer = MicroBitAccelerometer(i2c);
while(1) {
int x=uBit.accelerometer.getX();
int y=uBit.accelerometer.getX();
int z=uBit.accelerometer.getX();
stringstream result;
result << x << "," << y << "," << z;
uBit.serial.send(result.c_str());
uBit.serial.send("\r\n");
}
但是 result.c_str() 给了我一个错误错误:Class "std::basic_stringstream, std::allocator>" 在 "main.cpp" 中没有成员 "c_str",第 26 行,上校:34
screenshot
这可能是因为方法 send
只接受 const char*
而不是 std::string 作为参数。尝试:
uBit.serial.send(result.c_str());
编辑:
现在您的代码已经更改,结果是一个字符串流:
uBit.serial.send(result.str().c_str())
.
我正在尝试将来自 microbit 加速度计的整数 x y z 组合成一个字符串,然后将其发送到串口。我在这里使用在线 mbed 编译器中的 c++ 和 microbit DAL 库。
uBit.init();
uBit.serial.baud(115200);
MicroBitI2C i2c = MicroBitI2C(I2C_SDA0, I2C_SCL0);
MicroBitAccelerometer accelerometer = MicroBitAccelerometer(i2c);
while(1) {
int x=uBit.accelerometer.getX();
int y=uBit.accelerometer.getX();
int z=uBit.accelerometer.getX();
stringstream result;
result << x << "," << y << "," << z;
uBit.serial.send(result.c_str());
uBit.serial.send("\r\n");
}
但是 result.c_str() 给了我一个错误错误:Class "std::basic_stringstream, std::allocator>" 在 "main.cpp" 中没有成员 "c_str",第 26 行,上校:34 screenshot
这可能是因为方法 send
只接受 const char*
而不是 std::string 作为参数。尝试:
uBit.serial.send(result.c_str());
编辑:
现在您的代码已经更改,结果是一个字符串流:
uBit.serial.send(result.str().c_str())
.