简体   繁体   English

C中的命令行参数问题

[英]command line argument issue in C

I am assuming I am using this the wrong way, but the idea is for the command line argument to be the length of my fibonnaci serquence... however the way I am doing this, after 9 I am screwed... how can I resolve this issue? 我假设我以错误的方式使用它,但我的想法是命令行参数是我的斐波纳西序列的长度...但是我这样做的方式,9我被搞砸了...我怎么能解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
int fibonacci(int n)
{
  int first = 0;
  int second = 1;
  int total, i;
  for (i=0;i<n;i++)
  {
    printf("%d\n", first);
    total = first + second;
    first = second;
    second = total;
  }
  return 0;
}
int main(int argc, char *argv[])
{
    /*Spawn a child to run the program.*/
    pid_t pid=fork();
    if (pid==0) { /* child process */
        if(*argv[1] == 45){
            printf("number invalid \n");
        }else{
            int number = *argv[1] - 48;
            fibonacci(number);
        }
    }
    else { /* pid!=0; parent process */
        waitpid(pid,0,0); /* wait for child to exit */
    }
    return 0;
}

You should parse the command line argument using strtol , or similar, for example 例如,您应该使用strtol或类似方法解析命令行参数

number = strtol(argv[1],NULL,0);
/* last parameter gives the base, 0 detects hexadecimal (0x) and octal, defaults to 10 */

if you want to skip error checking. 如果你想跳过错误检查。 Cleaner, with error checking: 清洁,错误检查:

char *end;
number = strtol(argv[1],end,0);
if (end == argv[1])
{
    /* no valid digits */
    exit(EXIT_FAILURE);
}
if (*end)
{
    /* not all of argv[1] has been consumed
     * handle errors
     */
}
/* full parse of argv[1], no problems, carry on */

你的方式可以扩展到处理多个数字,但我认为你真正想要的是atoi()或非弃用的strtol()

尝试使用atoi功能。

Command line arguments are strings; 命令行参数是字符串; convert the strings to integers: 将字符串转换为整数:

int number = 9;
if (argc > 1)
    number = atoi(argv[1]);

This gives you a default value (9), and the option to override it. 这为您提供了一个默认值(9),以及覆盖它的选项。 More thorough checking would reject more than 1 argument, and negative or zero returns from atoi() : 更彻底的检查将拒绝多于1个参数,并且atoi()返回负或零:

enum { MAX_FIBONACCI = 47 };

if (argc > 2)
{
    fprintf(stderr, "Usage: %s [number]\n", argv[0]);
    exit(EXIT_FAILURE);
}
if (argc == 2)
{
    number = atoi(argv[1]);
    if (number <= 0)
    {
        fprintf(stderr, "Invalid number %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    else if (number > MAX_FIBONACCI)
    {
        fprintf(stderr, "Number %s is too large (max is %d)\n", argv[1], MAX_FIBONACCI);
        exit(1);
    }
}

Note that key information is reported to help identify what went wrong. 请注意,报告关键信息有助于识别出错的地方。 After 47 entries, you overflow a 32-bit signed integer. 在47个条目之后,溢出一个32位有符号整数。

Note that testing for errors from strtol() et al properly is a moderately complex business if you have to accommodate any return value whatsoever. 请注意,如果您必须提供任何返回值,那么正确测试strtol()等错误是一项适度复杂的业务。 If you only need to accommodate the range that you can print Fibonacci numbers for, it is rather simpler. 如果您只需要容纳可以打印斐波那契数字的范围,那就相当简单了。

The repeated four lines of error handling rapidly gets irksome. 重复的四行错误处理迅速变得令人厌烦。 I use a function like this instead: 我使用这样的函数代替:

#include <stdarg.h>

void err_exit(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    exit(EXIT_FAILURE);
}

This reduces the error reporting to one line per error, which is preferable to four lines. 这会将错误报告减少到每个错误一行,这比四行更可取。 (My full system is more complex than that, by quite a margin — all else apart, it gets told the program name and reports it automatically. But that's a workable starting point.) (我的完整系统比这更复杂,相当大的余地 - 除此之外,它会被告知程序名称并自动报告。但这是一个可行的起点。)

得到这样的论点:

int num = atoi(argv[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM