Sum of command line arguments?

So I am quite sure that just like last time I am missing something obvious, but in my programming class I keep trying this same problem and getting it wrong:

arg adder: Write a program  that prints one complete line of output  and nothing more. The output  it prints is just the sum  of its command-line arguments  (assume  they are all integers ).

For example, if the program  was invoked like this:
a.out 55 22 80 400
it would print out

I have come up with this:
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
	int total = 0, value;

	for (int i = 1; i < argc-1; i++)
		int value = atoi(argv[i]);
	cout << total << endl;

Codelab says that my code is outputting 0 when it should be 210. It does not tell me what the input is though. Any idea what I am doing wrong?
why are you looping to argc-1? Shouldn't you be looping to argc? By stopping at argc-1 you are not summing the last input value. This is probably what your problem is.

Also ... this is unrelated.... but you have two variables named 'value' defined. You define one on line 6, then define another on line 10. The one on line 6 is never used. (though really neither of them are needed, since you can just add the result of atoi to total directly). --- But again none of this matters as it's just stylistic things. These would not be causing the problem.
Between lines 10 and 11, print 'value' to the screen, that way you can see if your loop is going over your input like you expect it to. Also, how are you calling the program? What command line arguments are you passing to it?
Last edited on
Thank you Disch that was exactly my problem. Also thanks for the tip about value.

In lab I keep missing all these little details because it is separate from the regular course and we have not been taught these subjects at all. It took me several lab periods to even figure out how to use command line arguments at all!
Topic archived. No new replies allowed.