如何在C ++中将const char *转换为整数?

问题描述

我有这些变量。

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

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

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

解决方法

我为你做过榜样here

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...