简体   繁体   English

在C中使用int初始化char

[英]Initializing a char with an int in C

I am new to C programming and would like to create a char that puts text before an int. 我是C编程新手,想创建一个将文本放在int之前的char。

char charPin[] = ("PIN%d",pin);

I want it so I can pass charPin to an external function. 我想要它,因此可以将charPin传递给外部函数。 I am receiving an invalid initializer on the beginning of the line. 我在该行的开头收到无效的初始化程序。

You need a constant initialiser for incomplete arrays, so the compiler can determine the size at run-time. 对于不完整的数组,您需要一个常量初始化程序,以便编译器可以在运行时确定大小。 So it is not easily possible to use a variable for the pin-number. 因此,很难将变量用作引脚号。

If you can live with a constant pin, the following works: 如果您可以使用固定销钉,则可以进行以下操作:

#define STRINGIZE(x)    #x
#define CONCAT(a,b)     STRINGIZE(a##b)

static const char p10[] = CONCAT(PIN, 10);

int main(void)
{
    printf("%s\n", p10);
    return 0;
}

The # yields the argument enclosed with quotation marks, the concatenation operator ## concatenates the two arguments to a single one. #产生用引号引起来的自变量,串联运算符##将两个自变量串联成一个。 They are preprocessor operators, which is the reason this does not work with variables. 它们是预处理程序运算符,这就是它不适用于变量的原因。

A more useful example woud be to parametrize the pin-number only and use a macro to generate the rest of the text: 一个更有用的示例是仅对引脚号进行参数化,并使用宏来生成其余文本:

#define PIN(n)   STRINGIZE(PIN, n)

// usage:
... PIN(10) ...

That way you can change the text with just changing a single macro definition, eg for a different language: 这样,您仅需更改单个宏定义即可更改文本,例如针对另一种语言:

#define PIN(n)   STRINGIZE(Anschluss, n)

If you need a variable, you have to put some more effort into it. 如果需要变量,则必须付出更多努力。 However, if that is an example for the text you want to get, it might be easier to generate the names on-the fly along with the rest of the text you want to output, instead of storing into some array. 但是,如果这是您要获取的文本的示例,则可能更容易在运行时生成名称以及要输出的其余文本,而不是存储到某个数组中。

The best code depends on context you did not provide. 最佳代码取决于您未提供的上下文。

Your statement 您的声明

 char charPin[] = ("PIN%d",pin); 

is attempting to initialize an unspecified-length array of char with the expression ("PIN%d",pin) . 正在尝试使用表达式("PIN%d",pin)初始化char的未指定长度的数组。 That expression looks Pythonesque, but it is syntactically valid in C: the parentheses perform their ordinary grouping function around an expression involving the comma ( , ) operator. 该表达式看起来像Pythonesque,但是在C语言中在语法上是有效的:括号在涉及逗号( , )运算符的表达式周围执行其常规分组功能。 Evaluated in a context that actually allows that expression, the result would have the same type and value as pin . 在实际允许该表达式的上下文中进行评估,结果将具有与pin相同的类型和值。 That's not at all what you intend, and luckily the problem is of a type that the compiler rejects, as opposed to the one for which the compiler generates code to do the unintended thing you actually told it to do. 那根本不是您想要的,幸运的是问题是编译器拒绝的,而不是编译器生成代码来执行您实际上告诉它要做的意外操作的类型。

The initializer for an array of char can take either of two forms: char数组的初始化程序可以采用以下两种形式之一:

  • a string or UTF-8 literal, or 字符串或UTF-8文字,或者
  • a brace-enclosed array of individual elements. 用大括号括起来的单个元素数组。

Neither of those suits your purpose, so you'll have to fill the array with your desired contents separately from its declaration. 这些都不适合您的目的,因此您必须在数组中声明所需的内容,而不要声明其内容。 Moreover, that means you'll have to declare an explicit size for your array. 而且,这意味着您必须为数组声明一个显式的大小。 You need space for the text part (whose size you know), for the integer part (whose size is variable, within limits), and for a one-byte string terminator. 您需要空间来容纳文本部分(您知道其大小),整数部分(其大小是可变的,在限制范围内)以及一字节的字符串终止符。

If you're willing to make the very reasonable assumption that pin 's data type ( int ?) is no wider than 64 bits, then 20 characters will be sufficient for the maximum possible 19 decimal digits plus a sign, therefore 24 characters should be enough for the whole string. 如果您愿意非常合理地假设pin的数据类型( int ?)不超过64位,则20个字符将足以表示最大可能的19个十进制数字和一个符号,因此应为24个字符足以容纳整个字符串。 It's usually best to avoid magic numbers in your code, so you might declare charPin like so: 通常最好避免在代码中使用幻数,因此可以这样声明charPin

#define PIN_BUFFER_SIZE 24

// ...

char charPin[PIN_BUFFER_SIZE];

There are several ways you could fill set the array contents, but the most straightforward way for your case would be to use either sprintf() or snprintf() . 有几种方法可以填充设置数组内容的方法,但是最简单的方法是使用sprintf()snprintf() Suppose we're not entirely confident in our size computation, or that the text part is variable. 假设我们对大小计算不完全有把握,或者文本部分是可变的。 We might then declare a bit more space in charPin than we think we'll need, but ultimately we want to ensure that we do not overwrite the bounds of the array. 然后,我们可能会在charPincharPin比我们认为需要更多的空间,但是最终我们要确保不覆盖数组的边界。 snprintf() is intended for that purpose: snprintf()用于此目的:

int result = snprintf(charPin, PIN_BUFFER_SIZE, "PIN%d", pin);

That's the basic answer, but a careful programmer would not leave it at that. 这是基本的答案,但是细心的程序员不会那么做。 Supposing we want to be alerted in the event that our assumption about the needed space was wrong, instead of just letting the data be truncated, we would want to test the function's return value and handle any error that it indicates. 假设我们想在我们对所需空间的假设错误的情况下得到警告,而不是仅仅让数据被截断,我们还想测试函数的返回值并处理它指示的任何错误。 We would also want to check for a general error code, as generally we should do for every function call that can signal an error: 我们还希望检查一般的错误代码,就像通常情况下,我们应该为每个可能表明错误的函数调用一样:

if (result >= PIN_BUFFER_SIZE) {
    fprintf(stderr, "PIN truncated\n");
    exit(EXIT_FAILURE);  // or handle it some less-drastic way
} else if (result < 0) {
    // should not happen, but we're being thorough
    fprintf(stderr, "Internal I/O error\n");
    exit(EXIT_FAILURE);  // or handle it some less-drastic way
}

What you are looking for is the sprintf function. 您正在寻找的是sprintf函数。 First you have to declare an array big enough to store the result ( which might not be easy , so in my example I'm using a fixed size of 50 characters), then using the function you initialize it with formatted data. 首先,您必须声明一个足够大的数组来存储结果( 这可能不容易 ,所以在我的示例中,我使用50个字符的固定大小),然后使用对格式数据进行初始化的函数。 You don't have to check the resulting string's length with strlen , because sprintf returns it already. 您不必使用strlen检查生成的字符串的长度,因为sprintf已经返回了它。

size_t arraySize = 50;
char charPin[arraySize];
int resultSize = sprintf(charPin, "PIN%d", pin);

If sprintf failed, resultSize will be a negative value. 如果sprintf失败,则resultSize将为负值。 You can handle it with 你可以用

if (resultSize < 0) {
    // react to failure here
}

Now to print the result you can use printf("%s", charPin); 现在要打印结果,可以使用printf("%s", charPin); .

If you are trying to initialize the char array with a constant value, you can just write the PIN number (52 in my example) inside a string literal. 如果您尝试使用恒定值初始化char数组,则只需在字符串文字中写入PIN号(在我的示例中为52)。

char charPin[] = "PIN52";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM