C 中的命令行参数问题

标签 c command-line-arguments

我假设我使用了错误的方式,但这个想法是让命令行参数成为我的斐波那契序列的长度...但是我这样做的方式,在 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;
}

最佳答案

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

关于C 中的命令行参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594308/

相关文章:

c - 为什么在添加初始化静态变量时 .bss 大小会减小?

c - 调用 setsid() 的进程的子进程会怎样?

c++ - 检测 32 位双字 + 双字进位/C++

c# - Parser.Default.ParseArguments 始终返回 false

mpi - MPI 运行时传播 argc 和 argv 的内容

rust - 有没有一种方法可以设置Clap或另一个arg lib来接受普通的 '-'或 '+',这样我就可以获得没有命名标志的参数组?

linux - 什么是 Linux test -a 命令测试?

c - "statically allocated"在 libc 中到底意味着什么?每个库实例一个?每个程序实例一个?

C - while (某事 || 某事)

Python:从 optparse 切换到 argparse