C 字符串大小和数组

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

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

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

当我找到 key 字符串的大小

 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;

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

最佳答案

#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);
}

关于C 字符串大小和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22485956/

相关文章:

c - 从重定向的 stdin 读取(字数)- C

c - 使用fortran程序调用c子程序时打印语句乱序

c - Execvp(argv[1], argv),不返回那个文件或目录

c - 字符串声明中 `char *str`和 `char str[]`的区别

java - 将数组传递给方法

在 C 函数中更改数组

java - Android 中如何去掉不需要的字符?

c - 为什么我的程序在完成之前只接受一个输入?

mysql - SQL 如果子字符串出现则选择然后复制直到子字符串否则保持原始

javascript - 如何将 split() 函数与 html 标签和空格一起使用