Initializing string to a list of int values

#define VAL1 1
#define VAL151 151 // all values are from 0 to 254

char *str = {VAL1, VAL151, 0}; // of course it doesn't work

How to initialize a string with a set of defined values?
I use defined values elsewhere and want to initialize a string with a set of these values

char str[3] = { VAL1, VAL151, 0 }; // specifies a fixed-size string, I need to define a string containing any needed number of elements
Last edited on
std::string?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

// Avoid defines in C++:
const char VAL1 = 1;
const char VAL151 = 151;    // if char is signed, this will result in a warning that can be safely ignored.

int main()
{
    std::string str = { VAL1, VAL151 };

    std::cout << str;
}


code smell...

use unsigned char[] = {}; instead , char values are from -128,127
char values are from -128,127

The undecorated type 'char' has the same representation as either 'signed char' or 'unsigned char.' Which is up to the implementation.
@cire this is true , but prefer using unsigned and signed , it is less confusing about the range and tells exactly what we are looking for. you can also used type like __int8 or unsigned __int8 . (char -> 8 bits <=> 1 byte , always (except maybe in c# ...))
@cire this is true , but prefer using unsigned and signed , it is less confusing about the range and tells exactly what we are looking for.

In this case it would appear we're looking for the type c-strings are made of (which is char,) so it's less confusing to use exactly what we're looking for which is neither unsigned char nor signed char. ;)
correct.
I plan to use this construction as an element of the structure:
struct example {
std::string str1; // works OK
// unsigned char str2[]; // doesn't work, "zero-sized array in struct/union"
};
struct example example1[2] =
{
{ { 1, 2, 0 } },
{ { 1, 2, 3, 0 } }
};

Each array element will be initialized with a different numbers of values

std::string solution works fine

I am just curious, is it possible to declare and initialize just a char string in the same way without any classes like std::string?
Actually what I need is just a NULL-terminated string declared in a strange way
Topic archived. No new replies allowed.