【问题标题】:sscanf error: cannot convert 'String' to 'const char*'sscanf 错误:无法将 'String' 转换为 'const char*'
【发布时间】:2016-11-20 01:29:43
【问题描述】:

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

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 );

IDE 给我这个错误:

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++ 编译,在这种情况下标签也是错误的。请更新标签和问题。

标签: c++ string arduino char constants


【解决方案1】:

您可以尝试使用toCharArrayString 转换为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 );
    

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多