C produce error if no argument is given in command line

10,520

Solution 1

Given the code:

#include <stdio.h>

int main() {
  int input;
  int rc = scanf("%d", &input);
}

We can verify that scanf() was able to successfully get some input from the user by checking its return value. Only when rc == 1 has the user properly given us valid input.

If you'd like to know more, I recommend reading scanf's documentation.

Solution 2

Your question is inconsistent: if you want to get arguments from the command line, you must define main with argc and argv.

Your prototype for main is incorrect, it should be:

int main(int argc, char *argv[])

If the program is run without any command line arguments, arc will have the value 1. You can test it this way:

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("error: missing command line arguments\n");
        return 1;
    }
    ...
}

If you define main with int main(void) you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments.

Share:
10,520

Related videos on Youtube

Nicky Mirfallah
Author by

Nicky Mirfallah

A software engineer specializing in the .NET platform.

Updated on September 15, 2022

Comments

  • Nicky Mirfallah
    Nicky Mirfallah over 1 year

    In C, how can I produce an error if no arguments are given on the command line? I'm not using int main(int argc , * char[] argv). my main has no input so I'm getting my variable using scanf("%d", input)

    • Keith Thompson
      Keith Thompson about 8 years
      Then you're not looking at the command line, you're looking at an input line. What exactly do you mean by "no arguments'? What if the input is "Hello"? Or if the input is not empty, but consists only of spaces?
  • Keith Thompson
    Keith Thompson about 8 years
    And if the input syntactically looks like an integer but is outside the range represented by int, the behavior is undefined (this is a fundamental flaw of the *scanf() functions). The OP probably doesn't need to worry about that at this stage, though.