控制台输出在 C++ 中的 scanf() 方法上停止
console output halts on scanf() method in C++
我在库中使用以下方法读取来自蓝牙设备的数据:
BTSerialPortBinding::Read(buffer, length)
Reads data from the bluetooth device, returns number of bytes read
buffer: pointer to buffer to hold received data
length: maximum namber of bytes to read
当我使用 printf("%s", incomingData);
时,该方法很有效
将数据输出到控制台。
然而,当我使用 (scanf(incomingData, "6,%d,%d,%d\r\n", &x, &y, &z) == 3)
时,控制台似乎保持打开状态,但在尝试此行后不会输出任何内容。
数据源源不断的进来,以这种形式为例:
6, 211, 233, 232;
6, 392, 29, 93;
6, 42, 82, 94;
我希望扫描并提取最后三个值并将它们分别存储在一个 int 变量中。下面是我的代码,我在 Visual Studio 2015 上使用 windows 10 运行。
char incomingData[256] = "";
int dataLength = 255;
int readResult = 0;
while (1)
{
readResult = bt->Read(incomingData, dataLength);
incomingData[readResult] = 0;
// this prints fine
printf("%s", incomingData);
int x, y, z;
//stuck here
if (scanf(incomingData, "6,%d,%d,%d\r\n", &x, &y, &z) == 3) {
printf("x:%d,y:%d,z:%d\n", x, y, z);
}
Sleep(500);
}
如果您打算传递要解析的字符串,您需要 sscanf()
,而不是 scanf()
,它会执行 阻塞 从终端读取,这意味着什么都没有else 会在完成之前发生 - 它可能不会发生,因为您不希望在终端上提供数据。
您可能还需要以特定于平台的方式考虑行终止符。
我在库中使用以下方法读取来自蓝牙设备的数据:
BTSerialPortBinding::Read(buffer, length)
Reads data from the bluetooth device, returns number of bytes read
buffer: pointer to buffer to hold received data
length: maximum namber of bytes to read
当我使用 printf("%s", incomingData);
时,该方法很有效
将数据输出到控制台。
然而,当我使用 (scanf(incomingData, "6,%d,%d,%d\r\n", &x, &y, &z) == 3)
时,控制台似乎保持打开状态,但在尝试此行后不会输出任何内容。
数据源源不断的进来,以这种形式为例:
6, 211, 233, 232;
6, 392, 29, 93;
6, 42, 82, 94;
我希望扫描并提取最后三个值并将它们分别存储在一个 int 变量中。下面是我的代码,我在 Visual Studio 2015 上使用 windows 10 运行。
char incomingData[256] = "";
int dataLength = 255;
int readResult = 0;
while (1)
{
readResult = bt->Read(incomingData, dataLength);
incomingData[readResult] = 0;
// this prints fine
printf("%s", incomingData);
int x, y, z;
//stuck here
if (scanf(incomingData, "6,%d,%d,%d\r\n", &x, &y, &z) == 3) {
printf("x:%d,y:%d,z:%d\n", x, y, z);
}
Sleep(500);
}
如果您打算传递要解析的字符串,您需要 sscanf()
,而不是 scanf()
,它会执行 阻塞 从终端读取,这意味着什么都没有else 会在完成之前发生 - 它可能不会发生,因为您不希望在终端上提供数据。
您可能还需要以特定于平台的方式考虑行终止符。