3

我是一个普通的潜伏者,但这是我的第一篇文章!我知道你们喜欢细节,所以我会尽力而为。我会感激任何人的任何意见。

我正在为具有动态数字数组的对象重载提取运算符。控制台输入将具有前导空格,然后是 int,然后是后面的任何内容。我需要忽略空白,提取 int,然后不理会其余部分。容易吧?

这是我在网上找到的代码示例:

    istream & operator >> (istream &m, MyInt & p)
{
    int x = 0;
    p.currentLength = 0;
    while ((m.peek() == '\n') || (m.peek() == '\0') ||
           (m.peek() == '\t') || (m.peek() == ' '))
    {
        m.get();
    }
        while ((m.peek() >= '0') && (m.peek() <= '9'))
    {
        if (p.currentLength >= p.maxSize)
        {
            p.grow();
        }
        m >> p.theNumber[x];
        x++;
        p.currentLength++;
    }
    m.get();
    // reverse the order (i.e. - 123 to 321)
    char * temp = new char[p.maxSize];
        for (int y = 0; y < p.currentLength; y++)
    {
        temp[y] = p.theNumber[p.currentLength - 1 - y];
    }   
    delete [] p.theNumber;
    p.theNumber = temp;

    return m;
}

现在,我知道这种方法可能有效,但对我来说,这似乎是一种效率极低的方法。对于一万亿位数字,Grow() 将重新分配数组一万亿次!也许这并没有我想的那么糟糕?

我目前的方法是使用 seekg() 和 peek() 和 get()。像这样:

    istream& operator >> (istream& is, MyInt& z)
{
    int i = 0, j = 0;
    // check if next char is white
    while (is.peek() == 38)
    {
        j++;
        is.seekg(j); // skip if white
    }
    while (isdigit(is.peek()))
    {
        i++;
        is.seekg(j + i);
        if (!is.peek())
        {
            is.clear();
            break;
        }
    }
    is.seekg(j);
    z.length = i; 
    z.digits = new int[i + 1];
    for (i = 0; i < z.length; i++)
    {
        z.digits[i] = C2I(is.get());
    }
    return is;
}

另外,这是我的主要内容:

  int main()
{
    MyInt B;
    cout << "\n\nChange B to what num? ---> ";
    cin >> B;
    cout << "B is now: " << B;

    char c;
    cout << "\n\n\n\n\nEnter char to exit :   ";
    cin >> c;
    return 0;
}

对于我的生活,我找不到导致我的程序退出的原因。最后的输出似乎说,'B 现在:-1'

我相信这意味着 << B 失败。我目前已将 B 初始化为 0,并且我的其余代码没有出现其他问题。它的私有成员数据仅包括指针和长度(位数)。C2I() 也是一个将 '0' 到 '9' 转换为 0 到 9 的函数。

对我来说一个大问题是我对解析相当陌生,所以我没有非常雄辩的方法来测试这个或其他想法。

我再次感谢你们所做的一切。我已经从浏览这里学到了很多东西!

4

0 回答 0