What is the proper way to parse an integer from a string in Zig, while being able to specify the resulting integer type?
const foo = "96";
How would I convert foo to an i32, for example?
std.fmt.parseInt from the standard library is what you are looking for. It allows parsing integers of various types (u32, i64, u8, etc.), as well as bases (binary, hexadecimal, etc.).
Example:
const foo = "96";
const foo_integer = try std.fmt.parseInt(i32, foo, 10);
Inputting a value of 0 for the base allows parseInt to auto-detect the base for you based on prefixes.
0b - Base 2 (Binary)0o - Base 8 (Octal)0x - Base 16 (Hexadecimal)Another thing to note is that underscores (_) are safely ignored in the input string and will not throw a parse error.
You may also want to look at std.fmt.parseUnsigned if you expect only unsigned integers, it functions very similarly.