小编Sch*_*eir的帖子

自定义 strtoi 函数编译时问题

我正在尝试实现一个非常简单的strtoi功能。当动态创建传递的参数时,它工作正常(下面的情况 2)。但是,如果char[]在编译时分配的 char 是由which创建的,我会得到一个常量值,len因为std::strlen(ch)这会扰乱我的逻辑,我找不到解决方案。

 int strtoi(char* ch)
 {   
  int sum {0};
  int len = static_cast<int>(std::strlen(ch));
  int skipLast = static_cast<int>(static_cast<int>(ch[0]) == 45);

  //Integer Method
  for(int i = len - 1; i >= 0 + skipLast; i--)
  {
    if(static_cast<int>(ch[i]) < 48 || static_cast<int>(ch[i]) > 57)
      return 0;
    sum += (ch[i]-48) * std::pow(10,i-skipLast);
  }

   sum = skipLast == 1 ? -sum : sum;
   return sum;
 }

int main()
{
  char pos[3] {'1','2','3'};
  std::cout << strtoi(pos) …
Run Code Online (Sandbox Code Playgroud)

c++ compile-time-constant c++11

1
推荐指数
1
解决办法
58
查看次数

标签 统计

c++ ×1

c++11 ×1

compile-time-constant ×1