用C++将字符串转换为数字

问题描述 投票:0回答:1

我打算将一个字符串转换成一个数字数组。例如下面的代码很好用。

// A program to demonstrate the use of stringstream 
#include <iostream> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    string s = "12345"; 

    // object from the class stringstream 
    stringstream geek(s); 

    // The object has the value 12345 and stream 
    // it to the integer x 
    int x = 0; 
    geek >> x; 

    // Now the variable x holds the value 12345 
    cout << "Value of x : " << x; 

    return 0; 
}

但对于一个很大的字符串,我该怎么做呢?例如,字符串s="77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE"

arr[0]应该有0x77,arr[1]应该有0x98,以此类推。考虑到字符串s是64个字节,我的数组将是32个字节长。

谁能帮忙解决这个问题?

c++ arrays string stringstream
1个回答
0
投票

你可以尝试将输入的字符串分割成子串,每个子串的长度为2个字符。然后使用std::stoi()函数将十六进制子串转换为整数,并将每个转换结果存储到一个std::vector容器中。

#include <vector>
#include <iostream>


std::vector<int> convert(const std::string& hex_str) {

    std::vector<int> output;
    std::string::const_iterator last = hex_str.end();
    std::string::const_iterator itr = hex_str.cbegin();

    if (hex_str.size() % 2) {
        last--;
    }

    while(itr != last) {

        std::string sub_hex_str;
        std::copy(itr,itr+2,std::back_inserter(sub_hex_str));
        try {
            output.push_back(std::stoi(sub_hex_str,0,16));
        }catch(const std::exception& e) {
            std::cerr << sub_hex_str << " : " << e.what() << std::endl;
        }

        itr += 2;       
    }

    return output;
}

int main()
{
    std::string a = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE";

    const auto output = convert(a);

    for(const auto& a: output) {
        std::cout << a << std::endl;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.