C code freezes while running

I am just starting to learn the C programming language. I wrote this simple code that converts US dollars to euros. The only problem is that as soon as the USD input is entered, the program simply freezes. I use a while loop to ask the user if they want to repeat the operation, so I assume that the syntax of the code causes an eternal loop, but I'm not sure.

Here is my code:

#include<stdio.h>
#define conv 0.787033       //conversion factor of USD to Euro found www.ex.com//

int main(void)

{
    float USD, EURO;
    char cont = 'y';

    while (cont == 'Y' || cont == 'y')

    {
        printf("Please enter the amount of United States ");
        printf("Dollars you wish to convert to Euros\n");
        scanf("%f\n", &USD);

        EURO = USD * conv;

        printf("%.2f dollars is %.2f Euros\n", USD, EURO);
        printf("Do you wish to convert another dollar amount (Y/N)?\n");
        scanf("%c\n", &cont);
    }

    return(0);
}
+3
source share
3 answers

remove \nfromscanf

EDIT:

. scanf , , , scanf, , , , , .

fgets , , , sscanf.

scanf("%c%*c",&cont);. %*c .

C faq scanf

+12

\n scanf "ENTER" (Line Feed), . Enter ,

+5

scanf()


It is best to use fgets(3), then sscanf(3), because it is always imperative that the interactive program knows when the input line is expected.

So, the normal sane-scanf design pattern makes the program more complex, but also makes it more flexible and more predictable, try something like a change ...

scanf(...)

to

char space[100];
fgets(space, sizeof space, stdin);
sscanf(space, " %f", &USD);
+5
source

Source: https://habr.com/ru/post/1764634/


All Articles