在某种程度上类似于初始化字符串初始化字符数组 [英] initializing char arrays in a way similar to initializing string literals

查看:185
本文介绍了在某种程度上类似于初始化字符串初始化字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我下面一个字符数组初始化:

Suppose I've following initialization of a char array:

char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};

和我也有以下字符串字面量初始化:

and I also have following initialization of a string literal:

char stringLiteral[]="hello world";

第一阵列和第二串的内容之间的唯一区别是,第二串的得到在其端部一个空字符。

The only difference between contents of first array and second string is that second string's got a null character at its end.

在它的初始化字符数组的事,有没有宏或东西,使我们可以把两个双引号,但我们之间的初始化文本其中数组没有得到额外的空终止字符?

When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character?

这只是没有任何意义,我认为并不需要终止空字符的时候,我们应该用第一次提到的初始化语法和写在初始化文本的每个字符两个单引号,以及virgule痕单独的字符。

It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters.

我要补充一点,当我想有一个字符数组,它也应该是显而易见的,我不希望与依赖于字符串与没有的功能,使用字符串中的事实功能一起使用结果,是进入我的考虑。

I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration.

我很感激你的答案。

推荐答案

我可能已经找到了一种方法做我想做虽然它不是直接我想要的东西,但它很可能有同样的效果。结果
首先考虑以下两个类:

I might have found a way to do what i want though it isn't directly what I wanted, but it likely has the same effect.
First consider two following classes:

template <size_t size>
class Cont{
 public:
  char charArray[size];
};
template <size_t size>
class ArrayToUse{
 public:
  Cont<size> container;
  inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){}
};

在开始之前,你可能想要去的 这里 并看看恒前pression构造和初始化类型。结果
现在看看下面code:

Before proceeding, you might want to go here and take a look at constant expression constructors and initialization types.
Now look at following code:

const Cont<12> container={"hello world"};
ArrayToUse<11> temp(container);
char (&charArray)[11]=temp.container.charArray;

最后初始化文本在两个双引号之间写入。

Finally initializer text is written between two double quotations.

这篇关于在某种程度上类似于初始化字符串初始化字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆