-4
我是C++的初學者。我試圖按隊列順序(FIFO)寫一個動態分配的鏈表。該程序可以編譯並運行。但我無法打印任何東西。所以我不知道鏈接或打印輸出邏輯中是否存在問題。請幫忙。鏈接列表
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;
#include <iomanip>
using std::setw;
using std::left;
struct course
{
char coursename[32];
char term[32];
int unit;
char grade;
course* next;
};
void coutcourse(course*);
int main()
{
char input;
course *p;
course *prev;
course PHILO225 = {"PHILO-225", "SP2017", 3, 'A'}; // examples
course COMSC110 = {"COMSC-110", "SP2017", 4, 'A'}; //
course COMSC165 = {"COMSC-165", "FA2017", 4, 'X'};
course* start = 0;
course *t;
cout.setf(ios::left, ios::adjustfield);
while(true)
{
cout <<"Do you want to add a new course? [Y for yes, N for no]" << endl;
cin >> input;
if(input=='y'||input=='Y')
{
t= new course;
cout <<"Enter the name, term, units and grade for the new course in the same line, space separated." << endl;
cin >> t->coursename;
cin >> t->term;
cin >> t->unit;
cin >> t->grade;
for(p=start; p ; p=p->next)
{
t->next = 0;
if(start==0)
{
start=t;
p=t;
}
else
{
p->next=t;
p=t;
}
}
cout << endl <<setw(16)<<"COURSE"<<setw(16)<<"TERM" <<setw(16) <<"UNITS"<< setw(10)<<"GRADE" <<endl;
cout << "------------- -------- --------- -----------\n";
for (p=start;p;p=p->next)
coutcourse(p);
cout << endl;
continue;
}
if(input=='N'||input=='n')
break;
else
{
cout << "Invalid. Please try again." << endl;
continue;
}
}
for(p=start, prev=0; p ; prev=p, p=p->next)
{
if(p)
prev->next=p->next;
else
start=p->next;
delete p; // this can be written in another way. delete from start
}
}
void coutcourse(course* start)
{
cout<< setw(16) << start->coursename<< setw(16) << start->term << setw(16) << start->unit << setw(16) << start->grade << endl;
}
請告訴我錯誤在哪裏。謝謝。
其學習使用調試器的時間。 – Incomputable
建議:使用有意義的變量名稱。對空指針使用'nullptr'而不是0,並且''for''循環中使用't-> next = 0;'。 – user4581301