0

I am writing a simple converter to convert 3 metric measurements to British system values.I am supposed to write functions to solve it.

Below is the code I wrote.

#include <stdio.h>
void meter_to_feet(double,double);
void gram_to_pounds(double,double);
double Cel_to_Fahrenheit(double);

double target;
char letter;
int main(void){
    printf("How many values to convert? ");
    int time;
    scanf("%d",&time);
    //printf("%d\n",time);
    for (int i=0;i<time;i++){
        scanf("%lf",&target);     //problem occurs here 
        scanf("%c",&letter);      //and here
        if('m'==letter){
            meter_to_feet(target,3.2808);
        }else if('g'==letter){
            gram_to_pounds(target,0.002205);
        }else if('c'==letter){
            Cel_to_Fahrenheit(target);
        }
    }
    return 0;
}

void meter_to_feet(double x,double y){
    double r1;
    r1=x*y;

    printf("%0.6f ft\n",r1);
}

void gram_to_pounds(double x,double y){
    double r1;
    r1=x*y;
    printf("%0.6f lbs\n",r1);
}
double Cel_to_Fahrenheit(double x){
    double r1;
    r1=x*1.8+32;
    printf("%0.6f f\n",r1);
    return r1;
}

I give it a .txt file looks like below to test this code in a step-by-step terminal and it passed.

4
12 m
14.2 g
3.2 c
19 g

However, when I complie and run above code using clang, I only get results of first two metric measurements--12m and 14.2g. It omitted the last two for some reason. I figured that I have to change my two scanf() lines into scanf("%lf %c",&target,&letter);in order to get desired output. I wonder how exactly scanf() here, treats input in such scenario?

Limesisi
  • 3
  • 2
  • 1
    @Limesisi Apart from the `"%c"` versus `" %c"` issue which I failed to properly explain in my previous (now-deleted) comment, it turns out that you rarely want to use `%c` anyway, because it's so limited, and the error recovery is so poor in the case where the user accidentally types (or the file accidentally contains) two or more characters where a single character was expected. Soon enough you may have 2- or 3-character unit names, anyway. So you could declare something like `char unitname[6];`, and use `%5s` to read them, and `strcmp` to compare them. – Steve Summit Feb 07 '23 at 17:05
  • @Steve Summit- Thank you for answering my question. I just read a similar post here and figured out that scanf() consumes white-space, so if run the original code as it is, my third scanf() actually receives a white-space! and it just goes back to increment i value again , then in 2nd loop, it properly reads 12m as white-space got consumed by 1st time loop. How tricky! Yes, I'm new to C and this is an assignment which asks us to use %c. Thanks for your advice of using other specifiers, i'll keep in mind in the future:) – Limesisi Feb 07 '23 at 17:30

0 Answers0