c++

Convert non-null-terminated char* to int


I am working on some code that reads in a data file. The file frequently contains numeric values of various lengths encoded in ASCII that I need to convert to integers. The problem is that they are not null-terminated, which of course causes problems with atoi. The solution I have been using is to manually append a null to the character sequence, and then convert it.

This is the code that I have been using; it works fine, but it seems very kludgy.

char *append_null(const char *chars, const int size)
{
    char *tmp = new char[size + 2];

    memcpy(tmp, chars, size);
    tmp[size + 1] = '\0';

    return tmp;
}

int atoi2(const char *chars, const int size)
{
    char *tmp = append_null(chars, size);

    int result = atoi(tmp);

    delete[] tmp;   

    return result;
}

int main()
{
    char *test = new char[20];
    test[0] = '1';
    test[1] = '2';
    test[2] = '3';
    test[3] = '4';

    cout << atoi2(test, 4) << endl;
}

I am wondering if there is a better way to approach this problem.


Solution

  • int i = atoi(std::string(chars, size).c_str());