C++ 从istringstream读取输入,跳过第一个值C++;
这是一个作业,所以我不希望得到答案,但是非常感谢你朝着正确的方向轻推:) 我们被告知编写一个多项式类来包含指向int数组的指针。值大于0的每个索引都是多项式的一部分,因此(值)x^(索引),因此度只能为正 我的问题是为我们提供的测试代码,以及重载的输入运算符。因此,输入假设读取的第一个值是后面的值的数量,{5,3,7,-2,1,6}将是5个值,以升序排列到数组中。指数为0时为3,指数为1时为7,指数为2时为2,依此类推。问题是,我从讲师测试代码中读取的第一个值总是被跳过,一旦读取负值,代码就会中断 这是他的测试代码中创建要输入的istringstream的部分:C++ 从istringstream读取输入,跳过第一个值C++;,c++,input,operator-overloading,C++,Input,Operator Overloading,这是一个作业,所以我不希望得到答案,但是非常感谢你朝着正确的方向轻推:) 我们被告知编写一个多项式类来包含指向int数组的指针。值大于0的每个索引都是多项式的一部分,因此(值)x^(索引),因此度只能为正 我的问题是为我们提供的测试代码,以及重载的输入运算符。因此,输入假设读取的第一个值是后面的值的数量,{5,3,7,-2,1,6}将是5个值,以升序排列到数组中。指数为0时为3,指数为1时为7,指数为2时为2,依此类推。问题是,我从讲师测试代码中读取的第一个值总是被跳过,一旦读取负值,代码就会中
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;
谢谢你的帮助
buf+strlen(buf)
sprintf(buf+strlen(buf),“%d%d”,ci[k],k)中的buf+strlen(buf)的建议是什么代码>?@wesley.mesquita我希望我知道。。。我正在努力理解他的测试代码本身的大部分功能,我只是跟踪它对我的代码的功能:/。我也给他发了邮件,但他还没有回复。你怎么知道密码被破解了?当您输入负数时,它会做什么?@0x499602D2如果第一个值为负数,它将使用该值设置数组的大小,因此它会中断。假设第一个值必须为正,并且该值等于其后的值的数目。您能否显示设置系数
?
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;
}
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;
}