我正在写一些简单的c管理程序,它有一个仓库类,产品列表存储为链接列表 . 输出有两个问题:
-
输出id / s与输入的不同(但也类似)
-
有两个不同的打印功能,但只有一个在运行程序时执行(如果我评论了另一个,它们都可以运行)
由于程序编译没有任何错误,我试图逐行调试它,但似乎无法搞清楚
编辑:要清楚大学项目的这一部分,我不能使用标准库中的东西,如(std :: vector,std :: list,...)我需要手工实现链表
#include <iostream>
#include <iomanip> // std::setw
struct product {
int id;
int num;
product* next;
};
class warehouse{
private:
product* list = new product;
public:
warehouse() = default;
//adding a product to warehouse
void AddProduct(const int id,const int boxes) {
auto* item = new product;
auto* tmp = new product;
// copy the head of the linked list
tmp = list;
item->id = id;
item->num = boxes;
item->next = tmp;
//add the the new product at the beginning
list = item;
}
//print all products
void printlist() {
int i=0;
product* tmp;
tmp = list;
while(list) {
i++;
std::cout << "item n." << i << "\tid: " << tmp->id << " number of items: " << tmp->num << std::endl;
tmp = tmp -> next;
}
}
//print products that have less than 50 box and need resupply
void SupplyReport(){
product* tmp = new product;
tmp = list;
int i=0;
while(list) {
if (tmp->num <= 50) {
i++;
std::cout << i << ". id:" << tmp->id << std::setw(20) << "N. of Boxes:" << tmp->num << std::endl;
}
tmp = tmp -> next;
}
if (i==0)
std::cout << "No product/s need re-supply";
}
};
int main(){
/* Problems:
* Generating random id instead of using the given values
* Execute only one function at a time meaning if I commented printlist it's print the supply report as expected
*/
warehouse w1;
w1.AddProduct(005,50);
w1.AddProduct(007,70);
w1.AddProduct(055,30);
w1.printlist();
w1.SupplyReport();
return 0;
}
2 回答
For reference:
解决方案是简单地避免第一个数字为“零”的变量,或者将它们转换回十进制数
这种行为背后的原因是编译器将以'0'开头的值视为Octal文字!这就是输出不同但不随机的原因 . 我不知道这个“功能”,只是希望所有的ID都看起来很像
就像David的回答一样,只是通过改变while(list)到while(tmp)来解决这个问题,因为我觉得它基本上是相同的 .
固定代码是:
第一:
这很奇怪 . 你为什么要创造一个毫无意义的
product
并且指向list
?下一个:
您希望
tmp
指向list
还是希望它指向您创建和分配的new product
?它可以做这两件事中的任何一件,但它只能是一个指针 . 你想要它指向什么?下一个:
你有
while(list)
,但你想while(tmp)
.持续:
再次,你有
tmp
指向一个new products
然后你将它设置为list
. 你想tmp
指向同一个list
指向的东西吗?或者你想让它指向一个new product
?它不能两者兼得 .当你想要
while(tmp)
时,你再次拥有while(list)
.