Home > Enterprise >  How can I concatenate the elements of a vector of integers to a string in C ?
How can I concatenate the elements of a vector of integers to a string in C ?

Time:01-31

I've been trying to put every single element of a vector of integers into a string. I want to achieve this by type casting the integers into strings, after that I cocatenate those "small strings" into a single big string, which is going to represent all the elements of that specific vector.

This may look silly, but is really useful if you want to make a function that returns a vector like-a-thing, or etc.

The only problem is that I'm getting an error on line 13, which says :

error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(int&)’
   13 |     myString  = (string) myVector[i];
      |                                    ^

and I don't have the slightest idea on why this is happening. My code follows below :

#include <iostream>
#include <vector>
using namespace std;

int main()
{
  int myVector[5] = {1,2,3,4,5};

  string myString = "";

  for (int i =0; i < 5; i  )
  {
    myString  = (string) myVector[i];
    myString  = "\n";
  }

  cout << myString << endl;

any help will be much appreciated.

CodePudding user response:

You can use std::to_string to convert an int to a std::string.

Change this line:

myString  = (string) myVector[i];

To:

myString  = std::to_string(myVector[i]);

Note: concatenating strings like that might not be so efficient due to temporary strings being created and destroyed (although it is likely that small strings optimization will kick in, so no additional heap allocations will take place).
As @Someprogrammerdude commented, you can consider to use std::ostringstream.

Side notes:

  1. You are missing #include <string>.
  2. Why is "using namespace std;" considered bad practice?.

CodePudding user response:

You can use std::stringstream

#include <iostream>
#include <string>
#include <sstream>
int main()
{
    int myVector[5] = {1,2,3,4,5};
    std::string myString;

    std::stringstream sstream;
    for (auto i : myVector)
        sstream << i;

    sstream >> myString;
    std::cout << myString;
}

Link.

CodePudding user response:

You can use the fmt library:

  1. fmt::join will accept a range, in your case a vector of ints, and join its contents with a given separator (e.g. an empty string if you just want all of the elements together).
  2. fmt::format will create a string with a given format, in this case just the contents of the joined vector.

Demo

#include <fmt/ranges.h>

int main() {
  int myVector[5] = {1,2,3,4,5};
  auto myString = fmt::format("{}", fmt::join(myVector, ""));
  fmt::print("{}\n", myString);
}

// Outputs: 12345

Or, simpler, if you don't need the string:

int main() {
  int myVector[5] = {1,2,3,4,5};
  fmt::print("{}\n", fmt::join(myVector, ""));
}

The error you are getting is saying that the compiler cannot find a std::__cxx11::basic_string<char>::basic_string(int&) function, i.e., a std::string constructor accepting an int&.

CodePudding user response:

Overload the output stream operator, and then you have something reusable for a lot of scenarios.

Based on the feedback below overloading is not the best answer, another approach here : https://www.onlinegdb.com/zDUjVbSTp

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

// Overloading operator<< will have many benefits.
// you can use it to output an array to std::cout directly
// or you can write it to a file or stringstream
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
    os << "[";
    bool comma = false;
    for (const auto& value : values)
    {
        if (comma) os << ", ";
        os << value;
        comma = true;
    }
    os << "]";

    return os;
}

int main()
{
    std::vector<int> values{ 1,2,3,4,5 }; 

    // write directly to std::cout
    std::cout << "direct : " << values << "\n";

    // adding array to a string
    std::ostringstream os;
    std::string string{ "output = " };
    os << values;
    string  = os.str();
    std::cout << string << "\n";
    

    return 0;
}

CodePudding user response:

I'll add my own solution, as laid out in my comment:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

int main()
{
    std::vector myvector = { 1, 2, 3, 4, 5 };

    std::copy(std::begin(myvector), std::end(myvector),
              std::ostream_iterator<int>(std::cout, "\n"));
}
  • Related