Why do you need to? The String instance wraps a char array. Most functions that deal with char arrays can also handle Strings (though I think that was a mistake).
Use the toCharArray() function to get the char array from the String instance.
Why do you need to? The String instance wraps a char array. Most functions that deal with char arrays can also handle Strings (though I think that was a mistake).
Use the toCharArray() function to get the char array from the String instance.
Yes, i'm familiar with the downsides of Strings and that i should stick to char arrays.
But this little sketch were mostly for learning and experimenting. That's why i'm curious in how to get the sprintf to work with Strings.
From your post, i guess it isn't possible at all? (without using toCharArray())?
You could write a version of sprintf( ) where the third argument was an instance of the String class, or a pointer or reference to one, if you wanted to.
michinyon:
You could write a version of sprintf( ) where the third argument was an instance of the String class, or a pointer or reference to one, if you wanted to.
In that function, you'd still need to extract the char array from the String, so the advantages are minimal.
Great answers guys.
Now i know where the problem is and how to solve it.
For others who reads this and can't figure out what's going on (like my self a couple of days ago):
sprintf in use with Strings doesn't give a compiler error, the program hangs abruptly.
sprintf in use with Strings doesn't give a compiler error
sprintf takes a variable number of arguments, and does a variety of things with the arguments it gets. Trying to use one of the arguments incorrectly is a logic error, not a syntax error. The only one that can prevent logic errors is the programmer. The compiler can raise a "Hey, stupid, are you sure you want to do this?" flag.
sprintf(buf,"tmp= %s", tmp);Serial.println(buf); //----> hangs/crashes the program. WHY????
Here, you are promising the compiler that "tmp" is a pointer to a character array, terminated by a null character.
In reality, what you're doing is passing "sprintf" a pointer to the private storage of the String "tmp".