Greetings. Can you tell me how to convert char* to a string? Can I use printf function to output without converting char* like in C?
I honestly tried to find answers, but my skills were not enough.
I apologise for my English, it’s not my native language, I use a translator.
If you have a zero terminated char*
then the easiest way is to cast it to a ZString (which is the type for zero terminated strings), and just get a view from it:
char* my_cstring = ...
String my_string = ((ZString)my_cstring).str_view()
Regarding printf - if you talk about io::printf
then just casting the char* to ZString should make sure it is printed as a string.
char* my_cstring = ...
io::printfn("My string: %s", (ZString)my_cstring);
Thank you for the answers. That’s what I wanted to know.
Me again, hello. I want to clarify a couple of things.
I took the function (libcurl - curl_version()):
char *curl_version();
Found that the following code compiles and executes successfully:
import std::io;
extern fn String curl_version();
fn void main()
{
io::printfn("%s", curl_version());
}
Can you tell me why in this example I can substitute String
instead of char*
? Do you think this is a good practice or is it better to explicitly write char*
and then convert?
Wow it is amazing that works. Typically in this case you want to model the char *
as a ZString
which works nicely in C3.