Error converting int to C ++ string

advertisements

I'm working on this code that takes a numeric string and fills an array with each "digit" of the string. The issue I'm having is trying to convert an integer to a string. I tried using to_string to no avail.

Here is the code (note this is pulled from a larger program with other functions):

#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <typeinfo>

    int fillarr(int &length) {
        int arr[length];
        string test = "10010"; //test is an example of a numeric string
        int x = 25 + ( std::rand() % ( 10000 - 100 + 1 ) );

        std::string xstr = std::to_string(x); //unable to resolve identifier to_string
        cout << xstr << endl;
        cout << typeid (xstr).name() << endl; //just used to verify type change

        length = test.length(); //using var test to play with the function
        int size = (int) length;
        for (unsigned int i = 0; i < test.size(); i++) {
            char c = test[i];
            cout << c << endl;
            arr[int(i)] = atoi(&c);

        }
        return *arr;
    }

How can I convert int x to a string? I have this error: unable to resolve identifier to_string.


As mentioned by user 4581301, you need an #include <string> to use string functions.

The following, though is wrong:

arr[int(i)] = atoi(&c);

The atoi() will possibly crash because c by itself is not a string and that mean there will be no null terminator.

You would have to use a buffer of 2 characters and make sure the second one is '\0'. Something like that:

char buf[2];
buf[1] = '\0';
for(...)
{
   buf[0] = test[i];
   ...
}

That being said, if your string is decimal (which is what std::to_string() generates) then you do not need atoi(). Instead you can calculate the digit value using a subtraction (much faster):

    arr[int(i)] = c - '0';