从istringstream读取输入,跳过第一个值C ++

时间:2014-01-26 19:47:07

标签: c++ input operator-overloading

这是一个作业,所以我不期待一个答案,但非常感谢正确方向的推动:)!

我们被告知编写一个Polynomial类来包含一个指向int数组的指针。每个索引的值> gt; 0将是多项式的一部分,使得(值)x ^(索引),因此度数只能是正数。

我的问题是为我们提供的测试代码,以及我重载的输入操作符。因此输入假定读取的第一个值是将遵循的值的数量,因此{5,3,7,-2,1,6}将是5个值,以度数的升序放入数组中。因此3在索引0,7处在1,-2在2,依此类推。问题是,我从教师测试代码中读取的第一个值总是被跳过,一旦读取负值,代码就会中断。

这是他的测试代码的一部分,它创建了输入的istringstream:

  int tests[][16] = {
    { 0 },          // 0 (zero polynomial)
    { 1,  1 },      // 1
    { 1, -7 },      // -7
    { 2, 0, 1 },    // x
    { 2, 5, -1 },   // 5 - x
    { 3, 0, 0, 1 }, // x^2
    { 3, 1, -2, 1 }, // x^2 - 2x + 1
    { 3, -1, 0, 1 }, // x^2 - 1
    { 4, 0, 0, 0, 1 }, // x^3
    { 4, 2, -6, 6, -2 }, //
    { 5, 0, 0, 0, 0, 1 }, // 
    { 5, 4, 12, 20, 12, 4 },
    { 5, -1, 1, -1, 1, -1 },
    { 6, 0, 0, 0, 0, 0, 1 },
    { 6, 1, 5, 10, 10, 5, 1 },
    { 7, 0, 0, 0, 0, 0, 0, 1 },
  };

  int n_tests = 16;

  START_TEST((char*)"Operators");
  // Outer loop (for the first operand 'p')
  for (int i = 0; i < n_tests; i++) {
    int ci[256];
    int ni = tests[i][0];   
    for (int k = 0; k < ni; k++)
      ci[k] = tests[i][k + 1];

    // construct polynomial 'p' by way of the input operator
    char buf[1024] = "";
    for (int k = 0; k < ni; k++) {
      if (ci[k] != 0) 
    sprintf(buf + strlen(buf), "%d %d ", ci[k], k);
    }
    istringstream istr(buf);
    Polynomial p;
    istr >> p;

测试循环直到达到第三组值(1,-7)并首先读取-7,在尝试将数组调整为-7时打破代码。

这是我重载的输入操作符:

friend istream& operator >>(istream& input, Polynomial& arr) {

    int coeff = 0;   // holds the coefficient multiplied by the variable
    int nums = 0;    // holds the amount of integers to be input

    input >> nums;   // grab first input value

    if (nums > arr.size) {   // resize array if necessary
        arr.resize(nums);
    }

    for (int i = 0; i < nums; i++) {  // input coefficients at i index
        input >> coeff;
        arr.set_coeff(i,coeff);
    }
    arr.set_degree();
    arr.isFull();
    return input;
}

set_coeff:

int Polynomial::set_coeff(unsigned power, int coeff) {

    // resize pArray if power is out of bounds
    if (power >= size) {
        resize(power);
    }

    // insert value and reset attributes
    pArray[power] = coeff;
    set_degree();
    isFull();

    return power;
}

感谢您的帮助!

0 个答案:

没有答案