【问题标题】:C strings size and arrayC字符串大小和数组
【发布时间】:2014-04-24 12:33:03
【问题描述】:

我遇到了一个问题。我有以下示例

std::string key = "30 14 06 03 55 04 03 14 0D 2A";

当我找到密钥字符串的大小时

 size_t sizee = key.size();

结果是 29 很好。

但我想成为这样的输出

char data[10];
data[0] = 0x30;
data[1] = 0x14;
data[2] = 0x06;
data[3] = 0x03;
data[4] = 0x55;
data[5] = 0x04;
data[6] = 0x03;
data[7] = 0x14;
data[8] = 0x0D;
data[9] = 0x2A;

大小应为 10,考虑 30 为 1 14 为 2。 这个大小应该是数组的大小,就像字符串变成00 01一样,数组大小应该是2。

【问题讨论】:

  • 您知道自己想要什么没关系,但问题出在哪里,您尝试过吗?那是实际的目标语言? c 还是 c++?
  • ...但是您的 string 29 个字符长...
  • @vlad_tepesch 我应该如何处理 m 不知道是否应该先删除空格?

标签: c arrays string visual-studio-2010 visual-c++


【解决方案1】:
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
using namespace std;

int main(){
    string key = "30 14 06 03 55 04 03 14 0D 2A";
    istringstream iss(key);
    vector<char> data;
    unsigned x;
    iss >> hex;
    while(iss >> x){
        data.push_back(x);
    }
    size_t size = data.size();
    cout << "char data[" << size << "];" << endl;
    for(int i=0;i < size ; ++i){
        cout << "data[" << i << "] = 0x" 
             << hex << uppercase << setw(2) << setfill('0') <<  (unsigned)data[i] << ';' << endl;
    }
}

#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
#include <cstdlib>
using namespace std;

int main(){
    string key = "30 14 06 03 55 04 03 14 0D 2A";
    istringstream iss(key);
    vector<char> data;
    unsigned x;
    iss >> hex;
    while(iss >> x){
        data.push_back(x);
    }
    size_t size = data.size();
    cout << "char content[" << size << "];" << endl;
    unsigned *content;
    content = (unsigned*)malloc(size*sizeof(unsigned));
    for(int i=0;i < size ; ++i){
        //cout << "data[" << i << "] = 0x" << hex << uppercase << setw(2) << setfill('0') <<  (unsigned)data[i] << endl;
        content[i]=data[i];
        cout << "content[" << i << "] = 0x" << hex << uppercase << setw(2) << setfill('0') <<  content[i] << endl;
    }
    if(content[0] == 0x30)
        cout << "I get it." << endl;
    free(content);
}

【讨论】:

  • 非常感谢您的解决方案,但我在代码中添加了以下几行 unsigned *content;content = (unsigned)malloc(size); for(int i=0;i
  • @user3340847 ;应该是content = (unsigned*)malloc(size*sizeof(unsigned));
  • 先生,我想要这个输出内容[0] = 0x30;内容[1] = 0x14;内容[2] = 0x06;内容[3] = 0x03;内容[4] = 0x55;内容[5] = 0x04;内容[6] = 0x03;内容[7] = 0x14;内容[8] = 0x0D;内容[9] = 0x2A;从以下语句for(int i=0;i
  • 先生感谢您的回复,但问题不是这一行 cout
  • @user3340847 content[i] is 0x30 if display content[i] = 0x30.
猜你喜欢
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2020-10-18
  • 2023-03-07
  • 2016-03-05
  • 1970-01-01
  • 2022-12-17
  • 2012-12-27
相关资源
最近更新 更多