-2

i have an int array

int arr[]={192,168,1,0};

What is the best way to convert it into a string separated by dots so that i can obtain the following output:

192.168.1.0

sham
  • 61
  • 3
  • 9
  • 5
    Is it a coincidence, or are you always going to print only IPv4 addresses? – StoryTeller - Unslander Monica Feb 04 '19 at 08:20
  • What are you struggling with? You can loop through `arr` with `for (int &i : arr){ doSomethingWith(i)}`, convert `int` to `std::string` with `std::to_string` and append to a `std::vector` with `+=`. I think that's all you need for this task. – Blaze Feb 04 '19 at 08:25
  • 2
    Regarding the wanted "output", is it supposed to be `192.168.0.1` (as you show) or `192.168.1.0` (as the array is arranged)? Please edit your question to either fix possibly typos or to give more details. – Some programmer dude Feb 04 '19 at 08:27

6 Answers6

3

A completely generic approach, typical C++ style:

template <typename Iterator>
std::string join(Iterator begin, Iterator end, char separator = '.')
{
    std::ostringstream o;
    if(begin != end)
    {
        o << *begin++;
        for(;begin != end; ++begin)
            o  << separator << *begin;
    }
    return o.str();
}

Could be combined with a convenience function to avoid having to get the iterators all the time:

template <typename Container>
std::string join(Container const& c, char separator = '.') // can pass array as reference, too
{
    using std::begin;
    using std::end;
    return join(begin(c), end(c), separator);
    // not using std::... directly:
    // there might be a non-std overload that wouldn't be found if we did
}

The period as default separator might fit your need, but possibly is a rather bad choice for general, would we rather want to join with space?

If you modify the signature as follows:

template <typename Iterator, typename Separator>
std::string join(Iterator begin, Iterator end, Separator&& separator);

You could use arbitrary separators, as long as supported by operator<< – but you lose the default separator...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
2

you can use the intuitive std::ostringstream class here:

#include <sstream>
#include <string>
#include <iostream>

int main() {
    int arr[] = { 192,168,1,0 };

    std::ostringstream stream;
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
        if (i) stream << '.';
        stream << arr[i];
    }
    std::string string = stream.str();

    std::cout << string << '\n';
}

output:

192.168.1.0
Stack Danny
  • 7,754
  • 2
  • 26
  • 55
1

The most important thing is that there is no best way. You should get the confidence to develop your own style.

Assuming your array is always size 4 and your int values range from 0 to 255 (which I think is reasonable) I would do this

char buffer[99];
sprintf(buffer, "%d.%d.%d.%d", arr[0], arr[1], arr[2], arr[3]);
std::string ip_address(buffer);
dtell
  • 2,488
  • 1
  • 14
  • 29
john
  • 85,011
  • 4
  • 57
  • 81
1

You can use stringstream

#include <iostream>
#include <sstream>


int main(void)
{
    int arr[] = { 192,168,1,0 };
    std::stringstream ss;
    for (int i = 0; i < 4; ++i)
    {
        std::string sep = (i < 3) ? "." : "";
        ss << arr[i] << sep;
    }

    std::cout << ss.str() << std::endl;
}

or without conditional

#include <iostream>
#include <sstream>


int main(void)
{
    int arr[] = { 192,168,1,0 };
    std::stringstream ss;
    ss << arr[0] << "." << arr[1] << "." << arr[2] << "." << arr[3];


    std::cout << ss.str() << std::endl;
}
0

Define a string object into which put each elements of the int array by adding . character after each element except for the last one.

0

If the length of arr varies a basic code would be something like this:

#include <iostream>


int main()
{
    int arr[]={192,168,1,0};
    std::string output;
    size_t arr_size = sizeof(arr)/sizeof(arr[0]);
    for (int i=0; i<arr_size; i++)
    {
        output.append(std::to_string(arr[i]));
        //skip the last dot .
        if(i != arr_size-1)
            output.append(".");
    }
   std::cout << "output: " << output << std::endl; 
   return 0;
}
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67