通过C中的命令行传递整数? [英] Passing a integer through command line in C?

查看:70
本文介绍了通过C中的命令行传递整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以解释如何通过命令行传递参数?我真的对它的工作方式感到困惑。现在,我正在尝试将一个整数传递给主程序。我将如何去做呢?

I was wondering if someone could explain how passing arguments through command line works? I'm really confused by how it works. Right now I'm trying to pass one integer into the main program. How would I go about doing this?

编辑:不断获取初始化使指针产生整数,而没有强制转换[-Wint-conversion]错误?

keep getting the initialization makes integer from pointer without a cast [-Wint-conversion] error?

#include <stdio.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{ 
  double r,area, circ;

  char a = argv[1];
  int num =  a - '0';

  printf("You have entered %d",num); 

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}


推荐答案

签名对于C中的主要函数,将是这样:

The signature for the main function in C would be this:

int main(int argc, char *argv[]);

argc是传递给您程序的参数数量,包括程序名称本身。

argc is the number of arguments passed to your program, including the program name its self.

argv是一个包含每个参数作为字符串的数组。

argv is an array containing each argument as a string of characters.

因此,如果您这样调用程序,则: / p>

So if you invoked your program like this:

./program 10

argc 将是 2

argv [0] 将是字符串 program

argv [1] 将是字符串 10

您可以这样修改代码:

#include <stdio.h>
#include <stdlib.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
  double r,area, circ;

  char *a = argv[1];
  int num = atoi(a);

  printf("You have entered %d",num);

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}

您可能还想在打印语句中添加换行符可读性。

You probably also want to add line breaks into your print statements for readability.

这篇关于通过C中的命令行传递整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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