簡體   English   中英

如何在 c++ 中將 const char* 轉換為 integer?

[英]How can I convert const char* to integer in c++?

我有這些變量。

static constexpr int size{70};
const char* str;
std::array<int_least8_t, size> digits;

如果 str 是“1110”,我希望它是數字 [1,1,1,0]

int i=0;
while (*cci)
{
    digits[i]=*cci; // I need some method to convert it
    +cci;
    i++;
}

我在這里為你做了例子

#include <iostream>
#include <array>
#include <string>
#include <algorithm>

static constexpr int size{70};
const char* str = "1110";
std::array<int_least8_t, size> digits;

int main()
{
    int i = 0;
    for(auto c = str; *c; ++c, ++i) {
        digits[i] = *c - '0';
    }
        
    std::cout << "Count=" << i << std::endl;
    std::for_each(std::begin(digits), std::begin(digits) + i, [](const auto& Value) {
        std::cout << "Value=" << std::to_string(Value) << std::endl;
    });
    
    return 0;
}

Output:
Count=4
Value=1
Value=1
Value=1
Value=0

在 MSVC 編譯器中,我使用它看起來像

typedef signed char int_least8_t;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM