im writing a program that adds up command line arguments, how can i account for a situation where there are no arguments at all?

#include <iostream>

using namespace std;

int main(int argc,char *argv[]){
        int answer = atoi(argv[1]);
        if (argc=='0'){
              cout << '0';
        else if (argc == '1') 
             cout << answer;
        else {
             for (int j=2; j < argc; j++){
                     answer += atoi(argv[j]);
             cout << answer;
        return 0;

when i run the program w/o arguments i get a memory fault(coredump) error

8 Years
Discussion Span
Last Post by Freaky_Chris
if (argc=='0'){

Do you realise what you are doing here?
argc is a number representing the number of command line arguments passed to your program. '0' is equivelant to 48, so you say if 48 command line arguments are passed then do X. I expect that is now what you ment to do.

theoretically the following should work

  //display error message or whatever cause no arguments passed!

However we then get into a whidely debated topic about the minimal acceptable number of commandline arguments.

Many operationg system pass the file name (or executable path) tothe application by default making the default length equal to 1 and then additional command line arguments added by the users will increase from there.

However it is not written in C++ ANSI Standards that the first commandline argument passed is equal to the filename/exectuable path. Thu making this much more difficult than you imagine.

However it is a reasonably safe assumption to assume that the first argument is the filename/executable path. Thus you can use the following.

// no custom arguments add do something
// argv[1] is equal to the first argument the user passed!

Hope all this helps.
(i'm probably gonna get grilled by some experts now :D)


1  #include <iostream>
     3  using namespace std;
     5  int main(int argc,char *argv[]){
     6          int answer = atoi(argv[1]);
     7          if (argc==1){
     8                cout << '0';
     9          }
    10          else if (argc == 2)  
    11               cout << answer;
    12          else {
    13               for (int j=3; j < argc; j++){
    14                       answer += atoi(argv[j]);
    15               }
    16               cout << answer;
    17          }
    18          return 0;
    19  }

still get the memory fault error when i just provide one argument(the compiled code)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.