I am currently working on an assignment, part of which I am having trouble with. I need to be able to identify 5 different currency symbols ($, £, ¥, €, ₹) from the terminal and print them back. This is the function I assigned to complete this portion. We were told by the professors to use the UTF-8 code combinations for each of them to recognize the individual symbols. All that this function is attempting to do is see if the next character is one of the symbols, and if so print that specific symbol. If it doesn't recognize any of the 4 "foreign" currencies, it will default the symbol to being a $, even if it was a digit or different symbol. Thanks for the help!

determcur()
{
    char c = getchar();
    if(c == 0xC2)
    {
            c = getchar();
            if(c == 0xA3)
            {
                    printf("%c%c", 0xC2, 0xA3);
            }
            if(c == 0xA5)
            {
                    printf("%c%c", 0xC2, 0xA5);
            }
    }
    if(c == 0xE2)
    {
            c = getchar();
            if(c == 0x82)
            {
                    c = getchar();
                    if(c == 0xAC)
                    {
                            printf("%c%c%c", 0xE2, 0x82, 0xAC);
                    }
                    if(c == 0xB9)
                    {
                            printf("%c%c%c", 0xE2, 0x82, 0xB9);
                    }
            }
    }
    else printf("%c", 0x24);
}
有帮助吗?

解决方案

For a lot of C compilers a char is a signed 8-bit integer.

A signed 8-bit integer can only hold values from -128 to 127. They can not hold a value like 0x80, 0xE2, etc.

For something like if(c == 0xAC) the compiler knows that the value in c can't be higher than 127, and therefore knows that the condition must be false. For this reason, a compiler can optimise your code (by eliminating all code that can't be reached due to "must be false" conditions) down to getchar();printf("%c", 0x24);.

To fix this use uint8_t instead of char. If you can't find a uint8_t (e.g. you're stuck with an ancient dialect of C) then use an unsigned char.

However..

It's possible that the input is actually coming from a file or something and not coming from the keyboard at all. For this reason you should handle EOF properly. EOF will not fit in a (signed or unsigned) char and will not fit in a uint8_t either. This means you should store the value returned by getchar() in an int, then compare with EOF, then cast it to unsigned char or uint8_t with a type cast to compare it 0xAC.

Basically, it becomes a bit like this:

    int c;

    c = getch();
    if(c == EOF) exit(0);
    if( (uint8_t)c == 0xC2) {
        ...
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top