0

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.

5
  • 1
    Look at argv and argc. You get arguments from the command line. Minimal solution: int main(int argc, char *argv[]) { int cmdval = atoi(argv[1]); if (cmdval < 0) return 1; printf("%d\n",cmdval); return 0; } Commented Oct 5, 2016 at 19:20
  • Thanks. Please help and do not downvote or I 'll be kicked out from the forum. Commented Oct 5, 2016 at 19:22
  • 2
    I didn't downvote, but I can guess why someone did. People don't like wasting their time. On the surface your question looks like a copy-pasted homework assignment. Only your description of your research into scanf identified that your problem was with terminology (input vs arguments). Next time try posting a short program that doesn't work, but is close, and you'll probably have more success. Good Luck. Commented Oct 5, 2016 at 19:24
  • Nice explanation. I see. And your code actually works. Commented Oct 5, 2016 at 19:32
  • 1
    It works, but is terrible. Easy to break, no checks, no formatting, abuses return value, etc. But good enough for an example. :) Commented Oct 5, 2016 at 19:36

1 Answer 1

1
#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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.