有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。
有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。
有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将[
int a=10
)转换为[char string[200]
)。
是,有使用printf
的字符串版本>
snprinf(string,200,"%d",a);
如果您想手动执行上述操作,也可以使用div和mod乘以10的循环来生成字符串。 [有关此https://stackoverflow.com/a/49615617/391691的示例,请参见另一个答案
要从字符串sscanf
,atoi
或atol
中获取整数,请返回>]
#include <stdio.h> #include <stdlib.h> void main(){ int a; char string[200]; a = 10; snprintf(string,200,"%d",a); printf("As string:%s As int:%d\n",string,atoi(string)); }
对我来说,这个问题的解释仍然不清楚,与以前的答案相比,这代表了对该问题的另一种解释https://stackoverflow.com/a/58584291/391691]
有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。
在此答案中,我将陈述最小的问题,该问题未提供以下任何内容的详细信息:
string
中整数的表示/编码如果此问题与将整数转换为ASCII表示形式有关,则answer by @Simson是您所需要的。
C允许您通过将char
数组强制转换为int*
来将整数[1]放入c样式字符串的任何位置。
// string: the array (char*) // pos: position in the array (size_t) // to_insert: the value to insert (int) (*(int*)(&string[pos])) = to_insert;
但请注意:这是大锤方法。执行此操作时必须非常小心,否则您的代码可能会在不同平台上显示未定义的行为。例如,您必须手动检查并回答:
sizeof(int)
uint16_t
,uint32_t
,...以下示例显示了所讨论方法的用法:
#include <stdio.h> void insert_at_pos(char* arr, size_t pos, int to_insert){ (*(int*)(&arr[pos])) = to_insert; } int main(void) { char string[200] = {0}; insert_at_pos(string, 3, 10); //print char by char as hex for (size_t i=0; i < sizeof(string)/sizeof(*string); ++i){ printf("%x ",(unsigned char)string[i]); } }
运行示例:
$ ./main 0 0 0 a 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[1]:通过“放置”,我可以原样理解。
有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如,将(int a = 10)转换为(char string [200])。