Search code examples
cstdin

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


I want to write a C program that takes positive integer n from standard input, and outputs n+1. It is supposed to work like this

./myprog 3   
--> returns 4

./myprog -2
--> crashes

I tried using scanf. But it does not take standard input from the command line. Any code template to help me out? Thanks.

Earlier, I also tried

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

   int c;

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

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

   return 0;
}

It does not give a command-line solution neither.


Solution

  • #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;
    }