开发者

C code hangs during operation

I'm just starting to learn the C programming language. I've written this simple piece of code that converts the USD to Euros. Only problem is that once the input of the USD is entered, the pro开发者_开发技巧gram just hangs. I'm using a while loop to ask the user whether or not they want to redo the operation, so my guess is that the syntax of the code is causing an eternal loop, but I'm not for sure.

Here's 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);
}


remove the \n from your scanf

EDIT:

The above change should not work. When reading input using scanf, the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf, which means the next time you read from standard input there will be a newline ready to be read.

One way to avoid is to use fgets to read the input as a string and then extract what you want using sscanf.

Another way to consume the newline would be to scanf("%c%*c",&cont);. The %*c will read the newline from the buffer and discard it.

C faq on problems with scanf


the \n inside scanf require the user to press another extra "ENTER" (Line Feed) in order to continue. Remove it or you press Enter a few time, it will continue


Avoid scanf()


It's best to use fgets(3) and then sscanf(3) because it is invariably the case that an interactive program knows when a line of input is expected.

So, the usual sane-scanf design pattern does make the program a bit more complex but will also make it more flexible and more predictable, try something like changing...

scanf(...)

to

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜