skip to Main Content

I am currently developing a function that converts a list of values to integers. In the case of float types, we have the convenient float8in_internal_null() function at toFloatList(), which returns the appropriate float value if the conversion is successful, but returns NULL if the conversion of a list element fails.

However, when working with integers and using the atoi() function, I encountered a limitation. Unlike float8in_internal_null(), atoi() does not return NULL when it fails to convert an element of the list to an integer. Instead, it returns 0.

Is there an alternative function within some library in AGE, that can help me achieve the desired behavior of returning NULL when a conversion to an integer is not possible? I would appreciate any guidance on this matter.

2

Answers


  1. You can use check if the string you need to convert is zero, if it’s not zero and atoi() returns 0, then the string cannot be converted to an integer. Therefore, you can return or pass NULL.

    int result = atoi(string);
    if (strcmp(string, "0") != 0 && result == 0)
    {
        return NULL;
    }
    

    Additionally, if you want you can use the function age_tointeger from AGE, calling this function inside your C function using DirectFunctionCall.

    Login or Signup to reply.
  2. In C or C++, there is no special value like null or None like other languages. NULL in C-C++ is just a macro that defines it as 0. So, unlike other languages, C-C++ functions return 0. You need to add an additional check to verify if the case is an error or if 0 is the right answer.

    #include <iostream>
    #include <string>
    
    int main() {
        int i = atoi(num);
        if (num!="0" && i == 0)
        {
            cout<<"Error"<<endl;
        }
    }
    

    Instead, if you can use C++ libraries, you can also use std::stoi. It raises an exception in such cases, which can be handled.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search