2

When I execute the program and I enter C or F and complete the process, this is the image of what I see:

Screen shot

I want to hide the line in the red rectangle. This is the code I have:

#include <stdio.h>

int main(void){
    float f,c;
    char var;
    int x;

    while(var!='x'){
        printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
        scanf("%c",&var);
        if(var=='c'){
            printf("Grad Celsius =");
            scanf("%f",&c);
            f=(c*1.8)+32;
            printf("%.2f Grad Celsius sind %.2f Grad Fahrenheit\n",c,f);
        }
        else if(var=='f'){
            printf("Grad Fahrenheit =");
            scanf("%f",&f);
            c=(f-32)/1.8;
            printf("%.2f Grad Fahrenheit sind %.2f Grad Celsius\n",f,c);
        }
        else if(var=='x'){
            printf("fertig !! chao\n");
        }
        else {
            printf("Ungiltige Umreechnungsart!!\n");
        }
    }
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • it works lol thank you –  Nov 07 '15 at 16:45
  • Aside: `while(var!='x')` note that `var` is an *uninitiliased variable* on the first loop. – Weather Vane Nov 07 '15 at 17:27
  • you also have to initialize `var`, otherwise `while(var!='x')` would be undefined behaviour. `printf("Ungiltige Umreechnungsart!!\n");` should be `printf("Ungültige Umrechnungsart!\n");`. – mch Nov 07 '15 at 17:28

1 Answers1

0

In your case that happens because you are locking for a given character using the scanf() and the newline left from the previous call to scanf().

If you call scanf( %c,&var) with a space before the %c formatting will fix the issue because it will match any white space of any size (including none and the space left from your previous newline at the call of scanf().

The function scanf() provides no buffer overflow protection, this is particularly a problem when you are reading multiple characters, for example scanf("%s",&var) and might become unsafe to use.

A better and safer way to do that is to use fgets():

 fgets (value, MAX_VALUE_SIZE, stdin);

You can then format the input to whatever you'd like using for example sscanf()

PeCosta
  • 537
  • 4
  • 13