user2532642
user2532642

Reputation: 53

How to convert part of a character array to a integer variable in C

I have a assignment in which I am supposed to take in a user's input in the form of:

double, char('C' for Celsius or 'F' for Fahrenheit)

and convert it into the other temp scale. To do this task, I wrote this program:

The Program

/*
  The purpose of these program is to convert a user's input and use it in a tempurate conversion programs.
  By Paramjot Singh

  Psuedocode:

  import all needed files

  ask for user's input.

  convert user's imput into 2 varibles: a double and a char

  if the char is 'c' convert the double to farinhiet
  if the char is 'c' convert the double to celius

  display the result.
*/

 #include <stdio.h>
 int main( )
 {
    char input[7];
    printf("Welcome to the Tempurate Conversion Enter a number followed by C or F, depending on if you what to convert a Celuis Temp to Farinheit or vice versa.");
    fgets(input, 7, stdin);
    /*if (in == 'C' || in == 'c') commnented out code
    {
        int f = 9 / 5 (inint + 32);
        printf("Input ", in, " Output: " f, " F");
    }
     else (inint == 'F' || inint == 'f')
    {
        int c = 5 / 9 (inint - 32);
        printf("Input ", in, " Output: " c, " C");
    }
     else 
    {
       printf("I told you to enter c or f. Restart the program.");
    } */

     /*to test what was entered*/
     printf(input);
     return 0;
}

My question is what would I do to convert part of the character array to a double.

Upvotes: 0

Views: 149

Answers (2)

JackCColeman
JackCColeman

Reputation: 3807

Per the printf statement:

printf("Welcome to the Tempurate Conversion Enter a number followed by C or F, depending on if you what to convert a Celuis Temp to Farinheit or vice versa.");

It looks like you expect the user to enter (for example): 23.5c

This implies a: scanf("%lf%c", &inDouble, &inChar); statement with NO intervening comma.` Note the change to the variable names.

Also, the tolower(inChar) will simplify some of your if logic.

Hope this helps.

Upvotes: 1

Kninnug
Kninnug

Reputation: 8053

Scan your input with sscanf:

sscanf(input, "%lf, %c", &inint, &in);

Edit: inint is a bit of a misleading name. You're supposed to read in a double, right?

Upvotes: 0

Related Questions