0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
JPlusPlus
  • 318
  • 1
  • 10
  • 1
    Have you tried anything yet? Have you looked through the docs? Have you got any failed examples? Have you explored the errors you have gotten? Being more specific may help. This may help, it took me 30 seconds to find https://github.com/ziglang/zig/issues/4142#issuecomment-573286768 - Note I did not down vote your question. – Daniel Tate Jun 22 '23 at 19:26
  • 1
    @DanielTate I've searched around and gotten a basic answer from the docs, however I'm a novice in Zig and I'd like to get an answer from someone more experienced that can give a detailed response. I also thought since there were no answers to this on Stackoverflow, this question could be useful for other people searching for an answer. – JPlusPlus Jun 22 '23 at 19:29
  • 2
    I understand, unfortunately the community here doesn't like questions like this, they like specificity. Outlining the exact operations you are looking to achieve with at least one psudo code example or failed attempt will make for a much higher quality question. It looks like you're asking 3 questions here ( from a glance ) – Daniel Tate Jun 22 '23 at 19:34

1 Answers1

1

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);
JPlusPlus
  • 318
  • 1
  • 10
  • Your example is not accurate. The `fmt.parseInt` function returns the error union, so the type of `integer` is not `i32` but `ParseIntError!i32` in this case. You have to use `try` keyword to get the value type: `const integer = try std.fmt.parseInt(i32, foo, 10);`. – KindFrog Jun 22 '23 at 22:57
  • @KindFrog Thank you for the correction, I'll make sure to edit the answer. – JPlusPlus Jun 22 '23 at 23:37
  • 4
    Please, use `try` instead of `catch unreachable`. You can only use this only because you're parsing a known string; you could have just written `const integer = 22;`. But if someone is looking for ways to parse a number, they'll likely have an unknown string and will need to handle errors properly. This answer will only confuse them. – sigod Jun 23 '23 at 12:07
  • @sigod Edited it. – JPlusPlus Jun 23 '23 at 19:26