ILikeTurtles
ILikeTurtles

Reputation: 1022

Accepting two arguments in order to add them together in C++

I wrote the below in C++ in order to accomplish a learning assignment I found. The goal is to accept two arguments and add them together before printing them out.

I compiled the program using g++ and attempted to run it by calling ./a.out 1 2. The results are 1. It does not seem to be printing out x + y and is simply showing the first argument. What am I doing wrong here? My expectation would be that I would display the number 3.

#include <iostream>
using namespace std;

int x, y, z;

int main( int argc, char *argv[] ) {
    y = atoi(argv[0]);
    x = atoi(argv[1]);
    z = (x + y);
    cout << z << endl;
    return 0;
}

Disclaimer - This comes from a text book but I am not doing this for homework. This is me trying to self teach myself C++.

Upvotes: 0

Views: 249

Answers (1)

pm100
pm100

Reputation: 50190

argv[0] is the name of the program. You need argv[1] and argv[2]

and BTW - the reason you get 1 is because atoi stops on the first non digit, in your case it stops right away and returns zero when reading the program name. So y = 0 and x = 1

Upvotes: 10

Related Questions