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

Recommended Answers

All 3 Replies

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

if(argc==0){
  //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.

if(argc==1){
// no custom arguments add do something
}else{
// 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)

Chris

1  #include <iostream>
     2
     3  using namespace std;
     4
     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)

thats because of this line
int answer = atoi(av[1]);

av[1] will not exist, unless ac >= 2

Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.