converting an array of integers to string

后端 未结 5 1728
闹比i
闹比i 2021-01-25 11:23

If I have an array that looks like

int digits[size] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 4}

I want to remove the leading zeros and to d

5条回答
  •  天命终不由人
    2021-01-25 11:55

    you can use C++11 function std::to_string() here is an example

    #include 
    #include 
    
    int main()
    {
       int size = 15;
       int digits[size] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 4};
       std::string result = "";
    
       for (int i = 0; i < size; i++)
       {
          if (!(digits[i] == 0 && result.size() == 0))
             result += std::to_string(digits[i]);
       }
    
       std::cout << result << std::endl;
    }
    

    you can check if a string is numeric using this function

    bool isNb(std::string str)
    {
      if (str.size() == 0)
        return false;
    
      for (int i = 0; i < str.size(); i++)
      {
        if (std::isdigit(str.at(i)) == false)
          return false;
      }
    
      return true;
    }
    

提交回复
热议问题