【问题标题】:Storing value of string into char array将字符串的值存储到 char 数组中
【发布时间】:2017-02-16 18:18:15
【问题描述】:

我正在尝试创建一个 Big Integer 类,但遇到了问题。我有一个重载的构造函数,这给了我一些问题。它应该接收一个字符串并将该字符串转换为称为m_numberstd::uint8_t*,跟踪位数,并跟踪为每个std::uint8_t* 分配的空间。数字向后加载,最低有效位为m_number[0]。我遇到的问题是将“0”存储到数组中。该函数适用于任何其他值,但如果字符串中包含“0”,则该函数将停止将值存储到std::uint_8*。 这是我的类定义:

      class BigInteger
    {
    public:
        BigInteger add(const BigInteger& rhs);
        BigInteger multiply(const BigInteger& rhs);
        void display();
        BigInteger();
        BigInteger(const BigInteger& rOther);
        BigInteger(int);
        BigInteger(std::string);
        BigInteger& operator=(const BigInteger & rhs);

    private:
        std::uint8_t* m_number;
        unsigned int m_sizeReserved;
        unsigned int m_digitCount;
}

这是我的重载构造函数:

BigInteger::BigInteger(std::string str) {
    m_digitCount = str.length();
    m_sizeReserved = m_digitCount;
    m_number = new std::uint8_t[m_sizeReserved];
    std::uint8_t* aArray = new std::uint8_t[m_sizeReserved];
    int j = str.length()-1;
    for(int i=0; i < m_digitCount; i++, j--) {
            aArray[i] = str[j]-'0';
    }
    for(int i=0; i < m_digitCount; i++) {
        m_number[i] = aArray[i];
    }
    delete[] aArray;

}

【问题讨论】:

  • 请提供minimal reproducible example。顺便说一句,你有两个 new 但只有一个 delete 闻起来像内存泄漏
  • “函数停止存储值”你确定吗?在我看来,当读取不存储它的字符串时会出现问题。您可以只使用 std::vector 来保存大小而不是读取到 nul 并假设它将以您的字符串的大小终止。
  • 让生活更简单,使用std::vector
  • 总体思路似乎是合理的。 ideone.com/UssjvB.
  • 我想你也可以等到你读到字符串后再去转换,即aArray[i] = str[j]-'0'; -> aArray[i] = str[j]; & 然后像for( int i = 0; m_number[i] != 0; ++i ) std::cout &lt;&lt; m_number[i]-'0';

标签: c++ arrays string uint8t


【解决方案1】:

问题在于 uint8_t 被视为无符号字符。

因此,如果您通过 cout 传递它,它会将您的 0 解释为 ASCII 的索引,即 '\0' 并停止。 所以你必须确保 cout 不会将你的整数信息解释为字符信息。

有关解决方案和更多信息,请参见此处: uint8_t can't be printed with cout

【讨论】:

  • 这个问题不是由 std::cout 引起的,因为我从来没有真正输出过值,这是存储值的问题
  • 如果不使用任何输出,怎么知道有问题?您可以在哪一行代码中检测到它没有存储值?
猜你喜欢
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多