• Linux
  • August 2018
    M T W T F S S
    « Jul   Sep »
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  
  • Meta

  • Follow me on Twitter

  • Advertisements

Feelin’ the need to code

Yesterday, I felt the need to code something so I wrote a little program to convert between Celsius and Fahrenheit. Writing functions to do the conversions was easy but it took me a while to figure out how I wanted to input the data. I thought about creating prompts within the program, maybe inside a loop for multiple conversions. What I really wanted to do was get the input from command line arguments.

With a little on-line research, I figured out how to get a number from the command line using strtol() and strtod() and using the results of those functions to determine the validity of the return value.

To get the temperature scale (Celsius or Fahrenheit) to convert from, I started off using the tests I used in FnLoC to call the help function and expanded on it to call the appropriate conversion functions. That resulted in a cumbersome set if nested if-else statements but it worked.

I took another look at the program and decided that replacing the nested if-else statements with a switch() would be better. I created a local variable to hold the command line argument and passed the first character of the string to switch(). If that character isn’t f, F, c or C, it defaults to printing an error message and calling up the help function to show the proper syntax.

It’s a rather mundane and basic program but it was a learning experience and a step forward in relearning the language.

The program has 60 lines of code with 52 lines in four functions (including main). The other eight lines are compiler directives (#include) and function declarations.

 

Advertisements
%d bloggers like this: