Как проверить первые два символа моего массива char в C? - PullRequest
0 голосов
/ 09 января 2020

Это код для создания аналогичной C библиотечной функции atoi() без использования каких-либо C подпрограмм библиотеки времени выполнения.

В настоящее время я застрял в том, как проверить первые две цифры массива char s, чтобы увидеть, начинается ли ввод с «0x».

Если он начинается с 0x, это означает, что я могу преобразовать его в шестнадцатеричное.

#include <stdio.h>

int checkforint(char x){
    if (x>='0' && x<='9'){
        return 1;
    }
    else{
        return 0;
    }
}

unsigned char converthex(char x){
    //lets convert the character to lowercase, in the event its in uppercase
    x = tolower(x);
    if (x >= '0' && x<= '9') {
        return ( x -'0');
    }
    if (x>='a' && x<='f'){
        return (x - 'a' +10);
    }
    return 16;
}

int checkforhex(const char *a, const char *b){
    if(a = '0' && b = 'x'){
        return 1;
    }else{
        return 0;
    }
}

//int checkforint
/* We read an ASCII character s and return the integer it represents*/
int atoi_ex(const char*s, int ishex) 
{
    int result = 0; //this is the result
    int sign = 1; //this variable is to help us deal with negative numbers
                //we initialise the sign as 1, as we will assume the input is positive, and change the sign accordingly if not

    int i = 0; //iterative variable for the loop
    int j = 2;

    //we check if the input is a negative number
    if (s[0] == '-') {   //if the first digit is a negative symbol 
        sign = -1;      //we set the sign as negative
        i++;            //also increment i, so that we can skip past the sign when we start the for loop
    }

    //now we can check whether the first characters start with 0x

    if (ishex==1){
        for (j=2; s[j]!='\0'; ++j)
            result = result + converthex(s[j]);
        return sign*result;
    }

    //iterate through all the characters 
    //we start from the first character of the input and then iterate through the whole input string
    //for every iteration, we update the result accordingly

    for (; s[i]!='\0'; ++i){
        //this checks whether the current character is an integer or not
        //if it is not an integer, we skip past it and go to the top of the loop and move to the next character
        if (checkforint(s[i]) == 0){
            continue;
        } else {
            result = result * 10 + s[i] -'0';
        }
        //result = s[i];
        }

    return sign * result;
}

int main(int argc)
{   
    int isithex;

    char s[] = "-1";
    char a = s[1];
    char b = s[2];

    isithex=checkforhex(a,b);

    int val = atoi_ex(s,isithex);
    printf("%d\n", val);
    return 0;
}

1 Ответ

1 голос
/ 09 января 2020

В вашем коде есть несколько ошибок. Сначала в C вы начинаете считать с нуля. Поэтому в main() вы должны написать:

char a = s[0];
char b = s[1];

isithex = checkforhex(a, b);

Затем в checkforhex() вы должны использовать == (два знака равенства) для сравнения, а не =. Итак:

if (a == '0' && b == 'x')

Однако, как указал Кайлум, почему бы не написать функцию для передачи указателя на строку вместо двух символов? Вот так:

int checkforhex(const char *str) {
    if (str[0] == '0' && str[1] == 'x') {
        ...
    }
}

А в main() назовите это так:

isithex = checkforhex(s);
...