从c中终端的执行行输入
我遇到的问题是我必须用 c 语言编写一个河内塔游戏,并且环数的输入不能在程序中,但代码必须在执行中读取环数。
示例: ./hanoitower 3
代码应将 3 作为输入。我怎样才能做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我遇到的问题是我必须用 c 语言编写一个河内塔游戏,并且环数的输入不能在程序中,但代码必须在执行中读取环数。
示例: ./hanoitower 3
代码应将 3 作为输入。我怎样才能做到这一点?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
命令行参数作为字符串通过 C 程序的 main() 函数传播。
在 int main(int argc, char *argv[]) 中,argc 是参数的数量,argv 是包含参数的字符串数组。请注意,程序名称本身始终是第一个“参数”。
由于参数作为字符串传递,您可能需要将
3
转换为整数,这可以使用atoi
函数来完成。这是一个开始:Command line arguments are propagated as strings through the main() function of your C program.
In
int main(int argc, char *argv[])
argc is the number of arguments, and argv is an array of strings containing the arguments. Note that the program name itself is always the first "argument".As the arguments are passed as strings, you likely need to convert your
3
to an integer, which can be done with theatoi
function. Here's a start:我强烈建议阅读一本好的 C 编程书籍(2020 年,现代 C)。
这比在这里提问要快得多。不要忘记阅读您的 C 编译器的文档(可能是 GCC)、您的 构建自动化工具(例如GNU make 或 ninja)和调试器(也许GDB)。如果您在 Linux 上编写代码,另请阅读高级 Linux 编程 和syscalls(2),以及文档GNU glibc (或 musl-libc,如果你使用它)。
然而,程序参数以空终止字符串数组的形式提供给主函数,通常声明它就像
使用
./hanoistower 3
运行程序,并且如果您的hanoistower.c
是你的源代码(你需要在启用调试和警告的情况下进行编译,即 Linux 上的gcc -Wall -g hanoistower.c -o hanoistower
),那么你就多了一个参数,因此argc == 2
argv[0]
是"./hanoitower"
字符串argv[1]
> 是"2"
字符串(使用atoi
将其转换为int
)argv[2]
是NULL
拜托,请学会使用调试器(Linux 上的
gdb
)。I strongly suggest reading a good C programming book (in 2020, Modern C).
It will be much faster than asking questions here. Don't forget to also read the documentation of your C compiler (perhaps GCC), your build automation tool (e.g. GNU make or ninja), and debugger (perhaps GDB). If you code on and for Linux, read also Advanced Linux Programming and syscalls(2), and the documentation of GNU glibc (or of musl-libc, if you use it).
Hovever, the program arguments is given as a null terminated array of strings to the main function, which is usually declared as
if you run your program with
./hanoistower 3
and if yourhanoistower.c
is your source code (which you need to compile with debugging and warning enabled, i.e.gcc -Wall -g hanoistower.c -o hanoistower
on Linux) then you have one extra argument, soargc == 2
argv[0]
is the"./hanoistower"
stringargv[1]
is the"2"
string (useatoi
to convert it to anint
)argv[2]
isNULL
Please, please learn to use the debugger (
gdb
on Linux).只需将
argc
和argv
添加到main
方法参数列表中,如下所示:然后使用
argv
作为用于指定代码中环数的变量。Just add,
argc
andargv
to the list ofmain
method parameters, as shown below:Then use
argv
as the variable to specify number of rings inside your code.