массивы — ошибка C ++: не удалось преобразовать указатель в ссылку (Netbeans)

Хорошо, я не уверен, правильно ли я назвал это, но вот проблема. Я продолжаю пытаться передать массив, содержащий определенные пользователем объекты Course, в функцию, но он выдает ошибку «Could not convert» (Course *) (& courseCatalog)».
Кроме того, извините, если мой код довольно трудно читать. Многое закомментировано, так что я могу проверить некоторые вещи.

Мой основной:

#include "cc.h"
int main(int argc, char** argv) {
bool again=1;
Course c;
ifstream catalogIn("catalog.dat");
ofstream catalogOut("catalog.dat");
Course courseCatalog[256];

loadInCourses(catalogIn, courseCatalog);

courseCatalog[getNumCourses(courseCatalog)+1]=addCourse();

loadOutCourses(catalogOut, courseCatalog);

return 0;
}

Мои функции:

#include "cc.h"
int displayMainMenu(){
int choice;
cout<<endl<<"**********MAIN MENU**********"<<endl;
cout<<"1. Print List Schedule"<<endl;
cout<<"2. Print Weekly Schedule"<<endl;
cout<<"3. Get Course"<<endl;
cout<<"4. Advanced Options"<<endl;
cout<<"0 to Quit"<<endl;
cout<<"*****************************"<<endl<<endl;
cout<<"Menu Choice: ";
cin>>choice;
return choice;
}
int displayAdvMenu(){
int choice;
cout<<endl<<"**********ADV MENU**********"<<endl;
cout<<"1. Add Course to Catalog"<<endl;
cout<<"2. Remove Duplicates"<<endl;
cout<<"0 to go Back"<<endl;
cout<<"****************************"<<endl<<endl;
cout<<"Menu Choice: ";
cin>>choice;
return choice;
}

Course addCourse(){
Course course;

cout<<"\nCourse name:\t\t";
cin.ignore();
cin.getline(course.name, CNAMESIZE);

cout<<"Course ID:\t\t";
cin.getline(course.id, CIDSIZE);

cout<<"Number of credits:\t";
cin>>course.credits;

return course;
}

void loadInCourses(ifstream & ifs, Course courseCatalog[]){
int i=0;
while(ifs>>courseCatalog[i].credits){
ifs.getline(courseCatalog[i].name, CNAMESIZE, ',');
ifs.getline(courseCatalog[i].id, CIDSIZE, ',');
ifs.getline(courseCatalog[i].professor, CPROFSIZE, ',');
ifs.getline(courseCatalog[i].semester, CSEMSIZE, ',');
ifs.get(courseCatalog[i].grade);
i++;
}
return;
}

void loadOutCourses(ofstream & ofs, Course courseCatalog[]){
for(int i=0; i<=getNumCourses(courseCatalog); i++){
ofs<<courseCatalog[i].credits<<
courseCatalog[i].name<<","<<
courseCatalog[i].id<<","<<
courseCatalog[i].professor<<","<<
courseCatalog[i].semester<<","<<
courseCatalog[i].grade<<endl;
}
}

Course findCourse(ifstream & ifs){
char attribute;
string needle;
int credits;
int name;
int id;
bool again=1;
int numLines = getNumLines(ifs);

cout<<"Search by (N)ame or (I)d? ";
cin>>attribute;
while(again){
switch(attribute){
case 'N': case 'n':
cout<<"Enter name of course: ";
cin>>name;
for(int i=0; i<numLines; i++){

}
break;
case 'I': case 'i':
cout<<"Enter course ID: ";
cin>>id;
break;
default:
cout<<"Invalid Attribute. Try Again."<<endl;
}
}
}

int getNumCourses(Course courseCatalog[]){
int numcourses=0;
for(int i=0;courseCatalog[i].credits!=0;i++){
numcourses++;
}
return numcourses;;
}

int getNumLines(ifstream & ifs){
char line[1];
int count=0;

while(ifs.getline(line, 1)){
count++;
}

ifs.close();
return count;
}

ostream& operator<<(ostream& os, const Course c){
os<<endl<<c.name<<endl<<c.id<<endl<<c.credits<<" cr hrs"<<endl;
return os;
}

Мой заголовочный файл:

#ifndef CC_H
#define CC_H

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;

const int PREREQ_SIZE = 15;
const int POSTREQ_SIZE = 15;
const int CNAMESIZE=40;
const int CIDSIZE=15;
const int CPROFSIZE=40;
const int CSEMSIZE=15;

struct Course{
char name[CNAMESIZE];
char id[CIDSIZE];
int credits;
char professor[CPROFSIZE];
char semester[CSEMSIZE];
char grade;
float timeStart;
float timeStop;
friend ostream& operator<<(ostream& os, const Course c);
};

Course addCourse();
int displayMainMenu();
int displayAdvMenu();
void printString(Course c);
void loadInCourses(ifstream & ifs, Course courseCatalog);
void loadOutCourses(ofstream & ofs, Course courseCatalog);
Course findCourse(ifstream & ifs);
int getNumCourses(Course courseCatalog[]);
int getNumLines(ifstream & ifs);

#endif

ОБНОВЛЕНИЕ № 1:

#include "cc.h"
int main(int argc, char** argv) {
bool again=1;
Course c;
char catalogFilename[128]="catalog.dat";
ifstream catalogIn(catalogFilename, ios_base::app);
ofstream catalogOut(catalogFilename, ios_base::app);
Course courseCatalog[256];

loadInCourses(catalogIn, courseCatalog);courseCatalog[getNumCourses(courseCatalog)+1]=addCourse();

loadOutCourses(catalogOut, courseCatalog);

return 0;
}

функции:

#include "cc.h"
int displayMainMenu(){
int choice;
cout<<endl<<"**********MAIN MENU**********"<<endl;
cout<<"1. Print List Schedule"<<endl;
cout<<"2. Print Weekly Schedule"<<endl;
cout<<"3. Get Course"<<endl;
cout<<"4. Advanced Options"<<endl;
cout<<"0 to Quit"<<endl;
cout<<"*****************************"<<endl<<endl;
cout<<"Menu Choice: ";
cin>>choice;
return choice;
}
int displayAdvMenu(){
int choice;
cout<<endl<<"**********ADV MENU**********"<<endl;
cout<<"1. Add Course to Catalog"<<endl;
cout<<"2. Remove Duplicates"<<endl;
cout<<"0 to go Back"<<endl;
cout<<"****************************"<<endl<<endl;
cout<<"Menu Choice: ";
cin>>choice;
return choice;
}

Course addCourse(){
Course course;

cout<<"\nCourse name:\t\t";
cin.ignore();
cin.getline(course.name, CNAMESIZE);

cout<<"Course ID:\t\t";
cin.getline(course.id, CIDSIZE);

cout<<"Number of credits:\t";
cin>>course.credits;/*<<"Enter semester: ";
cin.getline(course.semester);

for(int i=0; i<PREREQ_SIZE && choice==1; i++){
bool choice;
cout<<"Add PreReq?: ";
cin>>choice;
if(choice==1){
...
}
}

for(int i=0; i<POSTREQ_SIZE && choice==1; i++){
bool choice;
cout<<"Add PostReq?: ";
cin>>choice;
if(choice==1){
...
}
}  */

return course;
}

void loadInCourses(ifstream & ifs, Course courseCatalog[]){
cout<<"b*"<<endl<<courseCatalog[0];
int i=0;
while(ifs>>courseCatalog[i].credits){
ifs.getline(courseCatalog[i].name, CNAMESIZE, ',');
ifs.getline(courseCatalog[i].id, CIDSIZE, ',');
ifs.getline(courseCatalog[i].professor, CPROFSIZE, ',');
ifs.getline(courseCatalog[i].semester, CSEMSIZE, ',');
ifs.get(courseCatalog[i].grade);
i++;
cout<<"d*"<<endl<<courseCatalog[i];
}
cout<<"c*"<<endl<<courseCatalog[0];
return;
}

void loadOutCourses(ofstream & ofs, Course courseCatalog[]){
for(int i=0; i<=getNumCourses(courseCatalog); i++){
ofs<<courseCatalog[i].credits<<
courseCatalog[i].name<<","<<
courseCatalog[i].id<<","<<
courseCatalog[i].professor<<","<<
courseCatalog[i].semester<<","<<
courseCatalog[i].grade<<endl;
}
}

Course findCourse(ifstream & ifs){
char attribute;
string needle;
int credits;
int name;
int id;
bool again=1;
int numLines = getNumLines(ifs);

cout<<"Search by (N)ame or (I)d? ";
cin>>attribute;
while(again){
switch(attribute){
case 'N': case 'n':
cout<<"Enter name of course: ";
cin>>name;
for(int i=0; i<numLines; i++){

}
break;
case 'I': case 'i':
cout<<"Enter course ID: ";
cin>>id;
break;
default:
cout<<"Invalid Attribute. Try Again."<<endl;
}
}
}

int getNumCourses(Course courseCatalog[]){
int numcourses=0;
for(int i=0;courseCatalog[i].credits!=0;i++){
numcourses++;
}
return numcourses;;
}

int getNumLines(ifstream & ifs){
char ch;
int count=0;

while(ch=ifs.get()){
count+=(ch=='\n'?1:0);
}

ifs.close();
return count;
}

ostream& operator<<(ostream& os, const Course c){
os<<endl<<c.name<<endl<<c.id<<endl<<c.credits<<" cr hrs"<<endl;
return os;
}

заголовок:

#ifndef CC_H
#define CC_H

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;

const int PREREQ_SIZE = 15;
const int POSTREQ_SIZE = 15;
const int CNAMESIZE=40;
const int CIDSIZE=15;
const int CPROFSIZE=40;
const int CSEMSIZE=15;

struct Course{
char name[CNAMESIZE];
char id[CIDSIZE];
int credits;
char professor[CPROFSIZE];
char semester[CSEMSIZE];
char grade;
float timeStart;
float timeStop;
friend ostream& operator<<(ostream& os, const Course c);
};

Course addCourse();
int displayMainMenu();
int displayAdvMenu();
void printString(Course c);
void loadInCourses(ifstream & ifs, Course courseCatalog[]);
void loadOutCourses(ofstream & ofs, Course courseCatalog[]);
Course findCourse(ifstream & ifs);
int getNumCourses(Course courseCatalog[]);
int getNumLines(ifstream & ifs);

#endif  /* CC_H */

0

Решение

В cc.hэти строки:

void loadInCourses(ifstream & ifs, Course courseCatalog);
void loadOutCourses(ofstream & ofs, Course courseCatalog);

должно быть

void loadInCourses(ifstream & ifs, Course courseCatalog[]);
void loadOutCourses(ofstream & ofs, Course courseCatalog[]);

Также есть логическая ошибка в getNumLines, Если istream::getline Функция заполняет свой буфер до достижения конца строки, она не удаляет остальную часть строки. Вы получите остальную часть строки при последующих чтениях.

Вместо этого вы могли бы просто сделать ifs.get() и посчитай сколько \n происходят.

Эта функция закрывается ifs, Он вызывается только из findCourse, а также findCourse еще никогда не назывался. Но когда ты звонишь findCourseИмейте в виду, что вам нужно будет перемотать поток обратно к началу, если вы хотите снова прочитать файл (или заново открыть его).

0

Другие решения

Ваша ошибка должна состоять из 2 частей, не может быть преобразована из … и в …

Вы передаете From .. и сигнатура функции определяет to …

Два не одинаковы. Вы должны изменить сигнатуру функции, чтобы она соответствовала передаваемому From, или изменить то, что вы передаете, чтобы он соответствовал To, определенному прототипом функции.

Вы обнаружите, что чтение всей ошибки наиболее полезно, и вам, вероятно, следует подумать, что публикация всей ошибки стоит дополнительного времени, так как показывать нам ее часть почти бессмысленно. Что даст вам бессмысленные комментарии ..

Если то, что вы после — это функция, принимающая указатель на любой массив Course, то вы, вероятно, должны вызывать ее так:

Course (*courseCatalog)[]

Или просто:

Курс * couseCatalog

0

По вопросам рекламы [email protected]