【问题标题】:Pointer to string with spaces [closed]指向带空格的字符串的指针[关闭]
【发布时间】:2014-09-22 18:05:30
【问题描述】:

给定一个指针和一个包含这个指针大小的变量。

我必须做什么来创建一个 char 数组,其中包含每个字节的十六进制值,后跟一个空格。

输入:

char *pointer = "test"; 
int size = 5; 

输出:

"74 65 73 74 00" 

指针不一定是字符串,可以指向任意地址。

我可以打印,但不知道如何保存在变量中。

char *buffer = "test";
unsigned int size = 5;
unsigned int i;
for (i = 0; i < size; i++)
{
    printf("%x ", buffer[i]);
}

【问题讨论】:

  • 那么到目前为止你尝试过什么?
  • 你使用的输出语句是什么(很重要)?
  • 我需要一个带有该输出的字符串/字符数组

标签: c++ c string pointers int


【解决方案1】:

提示:由于您使用的是 C++,请查找 hex I/O 操纵器:
http://en.cppreference.com/w/cpp/io/ios_base/fmtflags

如果您想使用 C 风格的 I/O,请查找 printf 修饰符 %x,如 "0x%02X "

编辑 1:
要保存在变量中,使用 C 风格的函数:

char hex_buffer[256];
unsigned int i;
for (i = 0; i < size; i++)
{
    snprintf(hex_buffer, sizeof(hex_buffer),
             "%x ", buffer[i]);
}

使用C++,查找std::ostringstream

  std::ostring stream;
  for (unsigned int i = 0; i < size; ++i)
  {
    stream << hex << buffer[i] << " ";
  }
  std::string my_hex_text = stream.str();

【讨论】:

  • 我知道如何打印,我需要保存在变量中
  • 在你的下一篇文章中,请澄清。
  • 第二个提示:查找 ostringstream。
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>

char *f(const char *buff, unsigned size){
    char *result = malloc(2*size + size-1 +1);//element, space, NUL
    char *p = result;
    unsigned i;

    for(i=0;i<size;++i){
        if(i)
            *p++ = ' ';
        sprintf(p, "%02x", (unsigned)buff[i]);
        p+=2;
    }
    return result;
}
int main(void){
    char *buffer = "test";
    unsigned int size = 5;
    char *v = f(buffer, size);
    puts(v);
    free(v);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2019-01-15
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多