c++ - 如何在 C++ 中将 const char* 转换为整数?
问题描述
我有这些变量。
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;
推荐阅读
- mouseevent - Helix Toolkit 如何使用 MouseWheelEventHandler 运行其他类中的特定方法
- r - why does R convert a matrix to numeric when I select a range?
- r - Calculating memory usage in R Shiny Application
- ruby - How do I find the value which encompasses the most data points when combined with a tolerance?
- javascript - 通过 onclick 向 html 和 body 添加样式
- python - 当内核设置为无时,opencv Erosion 或 Dilation 将如何工作
- r - 当我使用 word2vec::word2vec 函数时,我在 R 服务器中反复退出会话
- regex - 正则表达式以升序选择匹配项
- java - spring boot 项目:应用程序运行失败但 gradle bootRun 在idea IDE中可以
- java - Gradle:“TaskExecutionException:任务':compileKotlin'的执行失败”