【问题标题】:Converting string to number in C++在 C++ 中将字符串转换为数字
【发布时间】:2020-09-14 09:59:48
【问题描述】:

我打算将一个字符串转换为一个数字数组。例如下面的代码运行良好:

// 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[32] 中。 arr[0] 应该有 0x77,arr[1] 应该有 0x98 等等。考虑到字符串 s 是 64 字节。我的数组长 32 个字节。

有人可以帮忙吗?

【问题讨论】:

  • 是否要将字符串的数字存储到数组中?
  • 因此,您实际上是在问如何将表示十进制数的字符串转换为表示十六进制数的字符串。可能值得注意的是,作为问题的输入和输出。
  • @Abhishek 是的。我的字符串代表十六进制数。
  • @goodvibration 我的字符串代表十六进制数。

标签: c++ arrays string stringstream


【解决方案1】:

您可以尝试将输入字符串拆分为子字符串,其中每个子字符串的长度为 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 2014-05-02
    • 2020-02-20
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多