I want to check if a given variable is a char. Right now, my function returns a string based on the elements of a vector.
The issue is if I give it a char vector, then to_string() gives me the numeric value of the character 'foo'. So where I want it to read:
a b
it instead reads
97 98
I would rather implement something into the function than create an overload, since I have two other overloads already for argument types vector<vector<T>>
and vector<array<T, 2>>
that need to run by the same logic and it would be messy to have six total functions rather than three.
/** to string for vector that has singular elements
* vtos : vector to string
**/
template <class T>
basic_string<char> vtos (vector<T> &v )
{
string ret;
int i = 0;
for ( T& foo: v )
{
ret.append(to_string(foo) + " ");
if (++i % 10 ==0)
ret.push_back('\n');
}
return ret;
}
++++++++++++++++++++++++++++++++++
EDIT: You can use the marked solution if you have C++17. I don't, so I decided to just use a default parameter.
EDIT 2: The marked answer now also includes an edit, check there for a pre-c++17 answer. Will leave my own here too.
template <class T>
basic_string<char> vtos (vector<T> &v, bool isChar=false)
{
string ret;
int i = 0;
for ( T& foo: v )
{
if (isChar)
ret.push_back(foo);
else
ret.append(to_string(foo));
ret.push_back(' ');
if (++i % 10 ==0)
ret.push_back('\n');
}
return ret;
}