#How to Add two optional variables
1 messages · Page 1 of 1 (latest)
if you are certain they have a value you can use either variable.? or, more secure, variable orelse your_preferred_way_to_handle_the_error
you can also use the if (optional_variable) |variable| pattern but it will get a bit more verbose
I am not sure I grasped the meaning of your question, if I don't don't hesitate to ask again
I am new to zig and I didn't know how to get user input like C function scanf or gets is there any way to get user inputs like C?
Getting user input is an OS thing, so yes you can.
In Zig's case, I would suggest something like this:
const stdin_handle = std.io.getStdIn();
const stdin = stdin_handle.reader();
const line = (try stdin.readUntilDelimiterOrEofAlloc(allocator, '\n', 4096).?;
defer allocator.free(line);
The 4096 is the maximum number of bytes to read before giving up - which is useful if the amount of data being read is very large, for instance.
But for a line of user input, a relatively small value is probably more useful, depending on exactly what you're doing.
yeah, it's a little more convoluted in Zig because you have to be very specific. In scanf you get a ton of implicit stuff
Right.
There also readUntilDelimiterOrEof which takes a buffer to write into instead of allocating, if that's more to your liking, as well, incidentally.
While compiling this code i got error
test2.zig:5:78: error: expected ')', found ';'
const line = (try stdin.readUntilDelimiterOrEofAlloc(allocator, '\n', 4096).?;
Oh, I missed a paren 🤣
Should be 4096))
Allocator also does not declared
Sure - you need to an allocator from somewhere.
You can make one like this for your purposes:
var gpa = std.heap.GeneralPurposeAllocator(.{}) {};
const allocator = gpa.allocator();
You can put this in main, and then pass this allocator around to anything that needs it.