tags:

views:

488

answers:

3

I am supposed to produce a program for my computer science class that reads two integers and outputs the product, sum, etc. for the two integers. How can make it where the program reads any two integers input before the program is run? The output is supposed to look like this, with x and y being any variables typed in(we are using Cygwin):

$ ./a x y

product of x and y

sum of x and y

I am a beginner so please dumb down explanations for me if you can.

Okay, I used int main(int argc, char *argv[]). I tried to assign argv[2] to x and argv[3] to y, but when I compile the program it says assignment makes integer from pointer without cast. What does this mean and how the heck do I fix it?

+12  A: 

Assuming the C language:

  • Command line arguments are found in the argv array - argv[1], argv[2] etc.
  • Converting a string argument to an integer can be done with the atoi function.
  • Output can be done with the printf function.

[Trying to teach you to fish, rather than providing a fish. Good luck!]

Paul Beckingham
+4  A: 

Assuming that you are using bash, you can use $1, $2, etc for those arguments. If, however, you are useing C, you're code should looks something more like this:

#include <stdio.h>
#include <stdlib.h>

main(int argc, char *argv[]) {
    if(argc<=1) {
        printf("You did not feed me arguments, I will die now :( ...");
        exit(1);
     }  //otherwise continue on our merry way....
     int arg1 = atoi(argv[1]);  //argv[0] is the program name
                                //atoi = ascii to int
     //Lets get a-crackin!
 }

Hope this helps.

Mike
+3  A: 

Firstly, if you run your C program as

./a x y

then a is argv[0], x is argv[1], and y is argv[2], since C arrays are 0 based (i.e. the first item in the array is indexed with 0.

Realize that argv is an array (or I've always thought of it as an ARGument Vector, though you might think of it as an array of ARGument Values) of character string pointers. So, you need to convert the strings to integers. Fortunately, C has library functions to convert ASCII to integer. Look at the stdlib.h documentation.

Good luck!

PTBNL