我如何编写一个从命令行获取整数的 C 程序?

How could I write a C program that takes an integer from command line?

我想编写一个 C 程序,从标准输入中获取正整数 n,并输出 n+1。它应该像这样工作

./myprog 3   
--> returns 4

./myprog -2
--> crashes

我试过使用scanf。但它不接受来自命令行的标准输入。任何代码模板可以帮助我吗?谢谢

之前我也试过

#include <stdio.h>
int main( ) {

   int c;

   printf( "Enter a value :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c );

   return 0;
}

它也不提供命令行解决方案。

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

int main(int argc, char * argv[])
{
     int n = atoi(argv[1]); // n from command line
     n = n + 1; // return n + 1
     printf("%d", n);

     return 0;
}