在c终端中从执行行输入 [英] Input from the execution line in the terminal in c

查看:90
本文介绍了在c终端中从执行行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我必须在c中编写一个hanois塔式游戏,并且环数的输入一定不能在程序中,但是代码必须在执行过程中读取环数.

示例:./ hanoistower 3

并且代码应该以3作为输入.我该怎么办?

解决方案

命令行参数通过C程序的main()函数作为字符串传播.

int main(int argc, char *argv[])中,argc是参数的数量,而argv是包含参数的字符串数组.请注意,程序名称本身始终是第一个参数".

由于参数是作为字符串传递的,因此您可能需要将3转换为整数,这可以通过atoi函数完成.这是一个开始:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   int rings;
   if(argc != 2) {
       printf("Usage: %s number-of-rings\n",argv[0]);
       return 1;
   }

   rings = atoi(argv[1]);
   printf("Using number-of-rings = %d\n", rings);
...

   return 0;
}

The problem that i have is that i have to write a hanois tower game in c and the input for the number of the rings must not be in the programm but the code must read the number of rings in the execution.

Example: ./hanoistower 3

And the code should get the 3 as the input. How can i do that?

解决方案

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 the atoi function. Here's a start:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   int rings;
   if(argc != 2) {
       printf("Usage: %s number-of-rings\n",argv[0]);
       return 1;
   }

   rings = atoi(argv[1]);
   printf("Using number-of-rings = %d\n", rings);
...

   return 0;
}

这篇关于在c终端中从执行行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆