Reputation: 85
I'm trying to extract two numbers separated by a space from a string and save them as two ints. For example:
if input_string = "1 95" then:
servo_choice = 1
input_number = 95
Code:
String input_string = "";
int input_number = 0;
int servo_choice = 0;
input_string = Serial.readString();
sscanf( input_string, "%d %d", &servo_choice, &input_number );
The IDE gives me this error:
exit status 1
cannot convert 'String' to 'const char*' for argument '1' to 'int scanf(const char*, ...)'
Edit: I guess
input_number = input_string.substring(1,5).toInt();
Actually works and does what I want. I'd still like to know how to get sscanf to work if possible.
Thanks for any replies in advance..
Upvotes: 3
Views: 2127
Reputation: 3541
The String
is a class, not a basic type. That means that you need a method to convert / return a pointer to char if you want to use it in a sscanf
. That method exists and it's called c_str()
.
So, your line has to be:
sscanf( input_string.c_str(), "%d %d", &servo_choice, &input_number );
Upvotes: 2
Reputation: 35368
You could try to convert your String
into a char
array with toCharArray and pass that to sscanf
. Something like that (not tested though)
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);
Upvotes: 2