stringintegerzig

How can I parse an integer from a string in Zig?


What is the best way to parse an integer from a string in Zig and specify the resulting integer type?

const foo = "22";

How would I convert foo to an i32, for example?


Solution

  • After looking through Zig's Standard Library Documentation, I've found std.fmt.parseInt, which allows you to parse a string to an integer of any size, signed or unsigned (e.g. i32, u64).

    Example:

    const foo = "22";
    
    const integer = try std.fmt.parseInt(i32, foo, 10);