sscanf错误:无法将'String'转换为'const char*'。

3

我正在尝试从一个字符串中提取由空格分隔的两个数字,并将它们保存为两个整数。例如:

if input_string = "1 95" then:
servo_choice = 1
input_number = 95

代码:

String input_string = "";
int input_number = 0;
int servo_choice = 0;

input_string = Serial.readString();
sscanf( input_string, "%d %d", &servo_choice, &input_number );

我的集成开发环境显示了如下错误:

exit status 1
cannot convert 'String' to 'const char*' for argument '1' to 'int scanf(const char*, ...)'

编辑:我猜

input_number = input_string.substring(1,5).toInt();

实际上这个功能已经可以正常使用并且达到了我的需求。如果可能的话,我仍然想知道如何使用sscanf。

提前感谢任何回复..


你正在编译C ++,在这种情况下,标记也是错误的。请更新标记和问题。 - 2501
2个回答

2
你可以尝试使用toCharArray将你的String转换为char数组,并将其传递给sscanf。类似于以下代码(未经过测试):
int buffer_len = input_string.length() + 1;
char buffer[buffer_len];
input_string.toCharArray(buffer, buffer_len);
sscanf(buffer, "%d %d", &servo_choice, &input_number);

2

String 是一个类而不是基本类型。这意味着如果你想在 sscanf 中使用它,你需要一个将其转换/返回char指针的方法。这个方法存在且被称为 c_str()

因此,你的代码行应该是:

sscanf( input_string.c_str(), "%d %d", &servo_choice, &input_number );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接