背景:我想制作一个程序,它可以将文本作为输入并将其存储在字符数组中。然后我会将数组的每个元素打印成十进制数。例如,“Hello World”将被转换为72、101等。我将使用它作为快速的ASCII2DEC转换器。我知道有在线转换器,但我想自己制作一个。
问题:如何分配一个大小未知的数组,并使它与我输入的文本完全相同的大小?所以当我输入“Hello World”时,它会动态地创建一个确切大小的数组,只能存储“Hello World”。我已经搜索了网路,但找不到任何我可以利用的东西。
背景:我想制作一个程序,它可以将文本作为输入并将其存储在字符数组中。然后我会将数组的每个元素打印成十进制数。例如,“Hello World”将被转换为72、101等。我将使用它作为快速的ASCII2DEC转换器。我知道有在线转换器,但我想自己制作一个。
问题:如何分配一个大小未知的数组,并使它与我输入的文本完全相同的大小?所以当我输入“Hello World”时,它会动态地创建一个确切大小的数组,只能存储“Hello World”。我已经搜索了网路,但找不到任何我可以利用的东西。
我看到你在使用C语言。你可以像这样做:
#define INC_SIZE 10
char *buf = (char*) malloc(INC_SIZE),*temp;
int size = INC_SIZE,len = 0;
char c;
while ((c = getchar()) != '\n') { // I assume you want to read a line of input
if (len == size) {
size += INC_SIZE;
temp = (char*) realloc(buf,size);
if (temp == NULL) {
// not enough memory probably, handle it yourself
}
buf = temp;
}
buf[len++] = c;
}
// done, note that the character array has no '\0' terminator and the length is represented by `len` variable
std::string input;
cin >> input;
char* str_to_ascii_codes(char* str)
{
size_t i;
size_t str_length = strlen(str);
char* ascii_codes = malloc(str_length*4+1);
for(i = 0; i<str_length; i++)
snprintf(ascii_codes+i*4, 5, "%03d ", str[i]);
return ascii_codes;
}
编辑:你在评论中提到希望将缓冲区调整到最佳状态。我在上面的示例中采取了捷径,通过使字符串中的每个条目具有已知长度,并且不修剪结果中多余的空格字符。这是一个更智能的版本,修复了这两个问题:
char* str_to_ascii_codes(char* str)
{
size_t i;
int written;
size_t str_length = strlen(str), ascii_codes_length = 0;
char* ascii_codes = malloc(str_length*4+1);
for(i = 0; i<str_length; i++)
{
snprintf(ascii_codes+ascii_codes_length, 5, "%d %n", str[i], &written);
ascii_codes_length = ascii_codes_length + written;
}
/* This is intentionally one byte short, to trim the trailing space char */
ascii_codes = realloc(ascii_codes, ascii_codes_length);
/* Add new end-of-string marker */
ascii_codes[ascii_codes_length-1] = '\0';
return ascii_codes;
}