0

Working on this assignment. Not sure how to get out of the while loop and I can't use anything more advanced than a while loop. I tried casting the int to a char but that didn't work. Below is my code. Any help would be appreciated.

/* This program has the user input a number. This number is then printed out in degrees F, C and K*/

#include <stdio.h>

#define KEL 273.16
#define CEL1 32
#define CEL2 0.5555

void temperatures(double temp);


int main(void)
{
    double tempF; // Temperature the user inputs

    char userinput; // Quit character the user inputs

    userinput = 'a';

    tempF = 0;

    printf("Enter a temperature in degrees Farenheit or enter q to quit:\n");
    scanf_s("%lf", &tempF);
    //scanf_s("%c", &userinput);

    while ((char)tempF  != 'q')
    {
        temperatures(tempF);
        printf("Enter a temperature in degrees Farenheit or enter q to quit:\n");
        scanf_s("%lf", &tempF);
        //scanf_s("%c", &userinput);

    }

    printf("Goodbye!\n");


    return 0;
}

void temperatures(double temp)
{
    double celsius;
    double kelvins;

    celsius = (temp - CEL1) * CEL2;
    kelvins = celsius + KEL;

    printf("%lf F is %lf degrees C or %lf degrees K.\n", temp, celsius, kelvins);


}
Markovnikov
  • 41
  • 4
  • 13

3 Answers3

4

You need to change your strategy.

  1. Read a line of text.
  2. If the first letter of the line is q, then exit.
  3. Otherwise, try to read the number from the line using sscanf.

Here's a version of main that does that.

int main(void)
{
   double tempF; // Temperature the user inputs
   char line[200];

   while ( 1 )
   {
      printf("Enter a temperature in degrees Fahrenheit or enter q to quit:\n");

      // Read a line of text.
      if (fgets(line, sizeof(line), stdin) == NULL )
      {
         break;
      }

      if ( line[0] == 'q' )
      {
         break;
      }

      if ( sscanf(line, "%lf", &tempF) == 1 )
      {
         // Got the temperature
         // Use it.
      }
      else
      {
         // The line does not have a number
         // Deal with the error.
      }
   }

   printf("Goodbye!\n");

   return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

You should read the input as string (scanning a string) and convert it (atof), than use strcmp to compare the input string with your exit command. You can also use isdigit to check your input (not try to convert anything that is not a number)

Community
  • 1
  • 1
Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
0

You can read characters with

char c;
while (c != 'q') {
    scanf("%c", &c);
    //parse command
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175