mateicoman
mateicoman

Reputation: 85

Fahrenheit to Celsius in C

I have to create a converter which converts from F to C and vice versa in C. The program should have two parameters the first being the type of conversion needed and the second the numbers of degrees that have to be converted e.g.: ./program -f 50.0 and the output:10.00°C = 50.00°F Also it has to use two functions f2c and c2f which do the conversion. This is my code, which runs fine, but it doesn't do anything as the ifs are not accessed for some reason.

#include <stdio.h>
#include <float.h>
#include <string.h>

float c2f ( float c);
float f2c ( float f);
int main(int argc, char *argv[])
{
  char fArg = "-f";
  char cArg = "-c";

  float arg2;
  sscanf(argv[1], "%f", &arg2);
  if(strcmp(argv[0], &cArg) == 0)
  {
    float fValue = c2f(arg2);
    printf("%f C = ", arg2);
    printf("%f F\n", fValue);
  }
  else if(strcmp(argv[0], &fArg) == 0)
  {
    float cValue = f2c(arg2);
    printf("%f C = ", cValue);
    printf("%f F\n", arg2);
  }

}

float c2f ( float c)
{
  float f;
  f = 9*c/5 + 32;
  return f;
}

float f2c ( float f)
{
  float c;
  c = ((f-32) * 5)/9;
  return c;
} 

Upvotes: 0

Views: 275

Answers (1)

dbush
dbush

Reputation: 223972

Two issues here:

First, you attempt to assign string constants to single characters:

char fArg = "-f";
char cArg = "-c";

Your compiler should have warned you about this. Change them to character arrays:

char fArg[] = "-f";
char cArg[] = "-c";

And modify the calls to strcmp to remove the address-of operator & from these variables.

Second, the first command line argument is actually the name of the program, not the first user argument. So anyplace you access an element of argv, increase the index by 1.

sscanf(argv[2], "%f", &arg2);
if(strcmp(argv[1], cArg) == 0)
...
else if(strcmp(argv[1], fArg) == 0)

Upvotes: 2

Related Questions