首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C程序从命令行读取输入

C程序从命令行读取输入
EN

Stack Overflow用户
提问于 2014-09-30 05:00:04
回答 1查看 1.3K关注 0票数 0

我想让这个程序从命令行读取指令。这是一个数字转换器的八进制->二进制和二进制->八进制。我不能在运行之前告诉它要转换成什么吗?例如,./conv八进制二进制11将得到八进制3。我以前在运行linux程序时使用过./script input ouput。

代码语言:javascript
复制
#include <stdio.h>
#include <math.h>
int binary_octal(int n);
int octal_binary(int n);
int main()
{
    int n;
    char c;
    printf("Instructions:\n");
    printf("Enter alphabet 'o' to convert binary to octal.\n");
    printf("2. Enter alphabet 'b' to convert octal to binary.\n");
    scanf("%c",&c);
    if ( c=='o' || c=='O')
    {
        printf("Enter a binary number: ");
        scanf("%d",&n);
        printf("%d in binary = %d in octal", n, binary_octal(n));
    }
    if ( c=='b' || c=='B')
    {
        printf("Enter a octal number: ");
        scanf("%d",&n);
        printf("%d in octal = %d in binary",n, octal_binary(n));
    }
    return 0;
}
int binary_octal(int n)  /* Function to convert binary to octal. */
{
    int octal=0, decimal=0, i=0;
    while(n!=0)
    {
        decimal+=(n%10)*pow(2,i);
        ++i;
        n/=10;
    }

/*At this point, the decimal variable contains corresponding decimal value of binary number. */

    i=1;
    while (decimal!=0)
    {
        octal+=(decimal%8)*i;
        decimal/=8;
        i*=10;
    }
    return octal;
}
int octal_binary(int n)  /* Function to convert octal to binary.*/
{
    int decimal=0, binary=0, i=0;
    while (n!=0)
    {
        decimal+=(n%10)*pow(8,i);
        ++i;
        n/=10;
    }
/* At this point, the decimal variable contains corresponding decimal value of that octal number. */
    i=1;
    while(decimal!=0)
    {
        binary+=(decimal%2)*i;
        decimal/=2;
        i*=10;
    }
    return binary;
}
EN

回答 1

Stack Overflow用户

发布于 2014-09-30 05:02:00

命令行选项通过argcargv传递给main

代码语言:javascript
复制
int main(int argc, char** argv)
{
    for(int i=0; i<argc; ++i)
    {
        printf("Option %d is %s\n", i, argv[i]);
    }
}

试着用各种命令行参数运行这个小程序,你很快就会明白的!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26108817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档