У меня есть задание на домашнюю работу, но я не понимаю, что не так с моим кодом. Переменная имени перепутана. Я просматриваю свой учебник, и я не вижу ничего плохого в моем коде. Пожалуйста помоги.
Имя должно храниться в массиве длиной 80, и это был единственный способ, которым я знал, как это сделать.
Я получаю много опыта java, поэтому я не знаю, есть ли синтаксис, который мне не хватает или что.
Спасибо за ваше время.
//import statements
#include <iostream>
#include <iomanip>
using namespace std;
//class declaration section
class Student
{
//declare private instance variables
private:
int ssn;
char* name[80];
const int ARRAYLENGTH =80;
//deckale public methods and constructor
public:
Student();
void setName(string);
int getSSN();
string getName();
void setSSN(int);
};
//class implementation section
Student::Student()
{
//set ssn equal to 99999999 by default
ssn = 999999999;
//set name equal to unassigned by default
string someString ="unassigned";
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < someString.length())
name[i] = &someString[i];
else
name[i]= "";
}
}
void Student::setName(string newName)
{
//assigns the newName to the char array
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < newName.length())
name[i] = &newName[i];
else
name[i]= "";
}
return;
}
int Student::getSSN()
{
return ssn;
}
string Student::getName()
{
//make a string from the char array to return a string
string name1 = "";
for(int i = 0; i < 80; i++)
{
name1 += *(name+i);
}
return name1;
}
void Student::setSSN(int num)
{
//check to make sure ssn isnt below or equal to 0
if (num > 0)
ssn = num;
return;
}
//main function
int main() {
Student student1, student2;
//changing name and ssn of student2
student2.setName("John Doe");
student2.setSSN(123456789);
//printing out information
cout<< "Name for student1 is "<< student1.getName() <<" and snn is "<< student1.getSSN() <<endl; //name should be unassigned and ssn should be 999999999
cout<< "Name for student1 is "<< student2.getName() <<" and snn is "<< student2.getSSN() <<endl; //name should be John Doe and ssn should be 123456789
return 0;
}
Это char* name[80]
объявляет массив указателей. Возможно, вам просто нужен массив символов, используя char name[80]
. (Который буквально является указателем на первый символ массива)
char* name[80]
- массив указателей. (Наверное, не то, что вы намеревались)
Вы меняете SSN Student2, но вы печатаете SSN ученика1
Некоторые ошибки, которые я мог указать в одном сканировании, следующие:
Это не верно :-
name[i] = &someString[i];
Вы пытаетесь взять адрес определенного символа в строке и затем выбросить его в char *.
Затем вы пытаетесь сохранить значение в int, которое находится за пределами его диапазона: -
ssn = 999999999;
Я действительно не думаю, что вы хотите сохранить 80 имен, похоже, что у ученика есть только одно имя.
char *name[80]
означает 80 имен, а не 80 символов!
В любом случае: вы не можете держать указатель на локальную переменную, вы делаете это во многих местах.
Поэтому вам лучше использовать const char*
а не string
значений. например:
изменить string someString ="unassigned";
to const char* someString = "unassigned"
function Student::setName(string newName)
должен быть Student::setName(const char* newName)
Другой вариант - копировать, а не просто назначать указатель. означает использование string name[80];
вместо char* name[80];
в этом случае: function Student::setName(string newName)
лучше быть Student::setName(const string& newName)
Этот код должен решить проблему.
//import statements
#include <iostream>
#include <iomanip>
using namespace std;
//class declaration section
class Student
{
//declare private instance variables
private:
int ssn;
char name[80];
const int ARRAYLENGTH =80;
//deckale public methods and constructor
public:
Student();
void setName(string);
int getSSN();
string getName();
void setSSN(int);
};
//class implementation section
Student::Student()
{
//set ssn equal to 99999999 by default
ssn = 999999999;
//set name equal to unassigned by default
string someString ="unassigned";
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < someString.length())
name[i] = someString[i];
else
name[i]= '\0';
}
}
void Student::setName(string newName)
{
//assigns the newName to the char array
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < newName.length())
name[i] = newName[i];
else
name[i]= '\0';
}
return;
}
int Student::getSSN()
{
return ssn;
}
string Student::getName()
{
//make a string from the char array to return a string
string name1 = "";
for(int i = 0; i < 80; i++)
{
name1 += *(name+i);
}
return name1;
}
void Student::setSSN(int num)
{
//check to make sure ssn isnt below or equal to 0
if (num > 0)
ssn = num;
return;
}
//main function
int main() {
Student student1, student2;
//changing name and ssn of student2
student2.setName("John Doe");
student2.setSSN(123456789);
//printing out information
cout<< "Name for student1 is "<< student1.getName() <<" and snn is "<< student1.getSSN() <<endl; //name should be unassigned and ssn should be 999999999
cout<< "Name for student1 is "<< student2.getName() <<" and snn is "<< student2.getSSN() <<endl; //name should be John Doe and ssn should be 123456789
return 0;
}
ARRAYLENGTH
в качестве емкости массива, чтобы избежать возможных различий между значением для ARRAYLENGTH
и емкостью массива, например, char name[ARRAYLENGTH];
,
char* name[80]
? Вы должны понять, хотите ли выchar* name[80]
или char name [80] - зависит от вашей рабочей области.