Hey i'm just practicing my knowledge of C so i've tried to make this crude calculator where you enter two numbers, type whether you want to multiply, add, subtract or divide and it returns the answer. My code is here:
Code:
/* SIMPLE CALCULATOR */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
int x, y, validInput, answer;
char multiplication, division, addition, subtraction;
validInput = (argc == 7);
validInput = validInput && sscanf(argv[1], "%d", &x); /*This is where values for x and y are inserted*/
validInput = validInput && sscanf(argv[2], "%d", &y);
if(!validInput)
{
printf("Insert any positive values for x and y and run again.\n"); /*exit if no numbers inserted*/
return(EXIT_FAILURE);
}
validInput = validInput && sscanf(argv[3], "%c", &multiplication);
validInput = validInput && sscanf(argv[4], "%c", &division);
validInput = validInput && sscanf(argv[5], "%c", &addition);
validInput = validInput && sscanf(argv[6], "%c", &subtraction);
if(x && y <= 0)
{
printf("Insert positive numbers");
return(EXIT_FAILURE);
}
printf("Do you want to use division, multiplication, addition or subtraction?\n");
if (scanf("%c",&multiplication))
{
answer = x * y;
return(answer);
}
if (scanf("%c",&division))
{
answer = x / y;
return(answer);
}
if (scanf("%c",&addition))
{
answer = x + y;
return(answer);
}
if (scanf("%c",&subtraction))
{
answer = x - y;
return(answer);
}
return 0;
However when I compile, it just comes up with the "Insert two positive values for x and y" message even after putting two numbers in. I get the feeling I need to assign memory for this, but im unsure as how to do this.
I'm also unsure whether validInput = (argc == 7); is correct either. Is 7 correct? I don't know what number to put here, in a previous example there were two values for the valid inputer and it had argc == 3.
Any help would be great thanks.
*EDIT* Also as well, should I be using if, else, if, else... etc? I've just got a line of if's... Got a feeling that isnt correct either.