const std = @import("std");
const stdout = std.io.getStdOut().writer();
const print = std.debug.print;
pub fn fibonacci(n: i32) i32 {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
pub fn main() !void {
var num: i32 = 15;
var i: i31 = 1;
var buf: [10]i32 = undefined;
const stdin = std.io.getStdIn().reader();
try stdout.print("enter a number: ", .{});
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
num = std.fmt.parseInt(i32, user_input, 10);
} else {
num = @as(i32, 0);
}
// creating a loop
while (i <= num) {
print("{} ", .{fibonacci(i)});
i += 1;
}
}
这是我编写的代码,用于接受用户输入的项数以打印斐波那契数列
我收到以下错误:
> zig build-exe fibonacci.zig
fibonacci.zig:23:46: error: expected type '[]u8', found '*[10]i32'
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
~~~^~~~~
fibonacci.zig:23:46: note: pointer type child 'i32' cannot cast into pointer type child 'u8'
fibonacci.zig:23:46: note: unsigned 8-bit int cannot represent all possible signed 32-bit values
/home/alex/program/ziglang/lib/std/io.zig:187:18: note: parameter type declared here
buf: []u8,
^~~~
referenced by:
posixCallMainAndExit: /home/alex/program/ziglang/lib/std/start.zig:617:37
_start: /home/alex/program/ziglang/lib/std/start.zig:424:40
3 reference(s) hidden; use '-freference-trace=5' to see all references
但是我无法像在 C 中使用 scanf() 函数一样正常接受用户输入。
有没有更好的方法在 Zig 中获取用户的输入
我尝试使用 heap page_allocator 而不是 buff[] 但仍然显示一些错误
首先,这个函数的
buf
参数需要一个 []u8
类型,但是你的代码有:
var buf: [10]i32 = undefined;
之后,如果您使用的是 Windows,您将遇到另一个问题 — Windows 使用
"\r\n"
作为行尾,而不仅仅是 "\n"
。因此,您需要检查并删除尾随的 "\r"
,否则您将得到 error: InvalidCharacter
。
最终代码是这样的:
var buf: [32]u8 = undefined;
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
if (@import("builtin").os.tag == .windows) {
const new_buf = std.mem.trimRight(u8, user_input, "\r");
num = try std.fmt.parseInt(i32, new_buf, 10);
} else {
num = try std.fmt.parseInt(i32, user_input, 10);
}
print("num is:{}\n", .{num});
} else {
num = @as(i32, 0);
}
我的母语不是英语,所以请随时指出任何语法错误。