Search code examples
cconverterstemperature

C SIMPLE Temperature converter / Celsius to Fahrenheit UNKNOWN errors & output


I just started programming in C a few days ago and have a few questions:

The following program converts Celsius into Fahrenheit and vice versa. I am getting a Segmentation fault error.

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

float c2f(float);
float f2c(float);

float Fahrenheit,Celsius;

int main(int argc, char *argv[])
{

/** 
 * Check for the expected number of arguments (3)
 * (0) program name
 * (1) flag
 * (2) temperature
 */
if (argc!=3)
    printf("Incorrect number of arguments");

if (!strcmp(argv[1], "->f"))
{
   // convert the string into a floating number
   char *check;
   float Celsius = strtod(argv[2], &check);

// process from celsius to fahrenheit
   Fahrenheit = c2f(Celsius);
   printf("%5.2f°C = %5.2f°F",Celsius, Fahrenheit);
}   
else if (!strcmp(argv[1], "->c"))
{
   // convert the string into a floating number
   char *check;
   float Fahrenheit = strtod(argv[2], &check);

   // process from fahrenheit to celsius
   Celsius = f2c(Fahrenheit);
   printf("%5.2f°F = %5.2f°C", Fahrenheit, Celsius);


}   
else
   printf("Invalid flag\n");
} // main


float c2f(float c)
{
  return 32 + (c * (180.0 / 100.0)); 
} 

float f2c(float f)
{
  return (100.0 / 180.0) * (f - 32);
}

Also, I want my output to be like this:

**> TemperatureConverter ->f 10.0

10.00°C = 50.00°F**

This should convert 10C into F.

For F to C, the output should be:

TemperatureConverter ->c 50.0

50.00°F = 10C**


Solution

  • the error is if (!strcmp(argv[1], "->f")

    it's missing a final parenthesis, should be

    if (!strcmp(argv[1], "->f"))
    

    and you made the same mistake twice. 1 paren for strcmp(), 1 for if()

    you should include string.h. Also, you should put you functions f2c and c2f before main.

    also you wrote

    prinf
    

    try with a t before the f

    printf
    

    finally you need

    exit(0);
    

    after the first if. eg

    if (argc!=3)
    {
        printf("Incorrect number of arguments");
        exit(0);
    }
    

    otherwise the rest of the program runs and you get seg fault. Welcome to programming.