0

I have written a program that takes two values and sums them up and then displays them as a single value.

but if add those two values it erroring in ziglang

const std = @import("std");

const print = std.debug.print;
const stdin = std.io.getStdIn().reader();

var buff: [1000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buff);
const alloc = fba.allocator();

pub fn main() !void {
    print("Enter value for A: ", .{});
    const value = try stdin.readUntilDelimiterOrEofAlloc(alloc, '\n', 100);
    const a = value.?;
    defer alloc.free(a);

    print("Enter value for B: ", .{});
    const value1 = try stdin.readUntilDelimiterOrEofAlloc(alloc, '\n', 10);
    const b = value1.?;
    defer alloc.free(b);

    const tot = a + b;

    print("A = {s}\n", .{a});
    print("B = {s}\n", .{b});
    print("A + B = {s}\n", .{tot});

error message:

alloc.zig:17:19: error: invalid operands to binary expression: 'Pointer' and 'Pointer'
    const tot = a + b;

I want to add two variables and to store into single variable

Aathiraj
  • 13
  • 5

1 Answers1

2

You must first parse the strings you get from readUntilDelimiterOrEofAlloc into numbers. You can use functions from std.fmt for that: parseInt, parseUnsigned or parseFloat.

For example:

const value_a = try std.fmt.parseInt(i64, a, 10);
const value_b = try std.fmt.parseInt(i64, b, 10);
const sum = value_a + value_b;
print("{} + {} = {}\n", .{value_a, value_b, sum});

Example output:

$ zig build run
Enter value for A: 123
Enter value for B: 111
123 + 111 = 234
sigod
  • 3,514
  • 2
  • 21
  • 44