Experiment 7-3-6 Convert a character string to a decimal integer (15 points)

Enter a string ending with #. This question requires filtering out all non-hexadecimal characters (not case sensitive) to form a new string representing hexadecimal numbers, and then convert it to a decimal number Output. If the character "-" exists before the first hexadecimal character, it means that the number is negative.

Input format:
Input a non-empty string ending with # in one line.

Output format:
output the converted decimal number in one line. The problem is guaranteed to be output within the long integer range.

Input sample:
±P-xf4±1! #Output
sample:
-3905
title collection complete works portal

#include <stdio.h>
#include <string.h>
#include <ctype.h>    //包含toupper()函数
int main()
{
    
    
    char c[100], ch[100] = {
    
     '\0' };
    int j, sum, n;
    j = sum = 0;
    gets(c);
    for (int i = 0; i < strlen(c); i++)
    {
    
    
        if (c[i] == '#')
            break;
        else if (c[i]=='-'||c[i] >= '0' && c[i] <= '9' || toupper(c[i]) >= 'A' && toupper(c[i]) <= 'F')
        {
    
    
            ch[j] = c[i];
            j++;
        }
    }

    for (int i = 0; i < strlen(ch); i++)
    {
    
    
        if (ch[i] != '-')
        {
    
    
            if (ch[i] >= 'A' && ch[i] <= 'F')
                n = ch[i] - 'A' + 10;
            else if (ch[i] >= 'a' && ch[i] <= 'f')
                n = ch[i] - 'a' + 10;
            else
                n = ch[i] - '0';
            sum = sum * 16 + n;
        }
    }

    if (ch[0] == '-' && sum != 0)
        printf("-%d", sum);
    else
        printf("%d", sum);

    return 0;
}

Guess you like

Origin blog.csdn.net/fjdep/article/details/112983749