With this little code, I have 2 issues, both surrounding the loop of mine.
I have a list of students' ages, and I want to input a value and loop all students lineary until it matches a student.
The other issue I found was that even if the value inside the loop is equal to what I'm checking, it wouldn't trigger my if statement. I tested this by searching for Age 1 while the first student in the list was also Age 1.
Here's my full code with 2 debug lines and a print screen of my run of it.
Apologies for not commenting my code yet.
#include <iostream>
#include <string>
usingnamespace std;
class Student
{
public:
string name;
int age;
void print()
{
cout << "Student: " << name << endl;
cout << "Age: " << age << endl;
}
void store(string _name, int _age)
{
name = _name;
age = _age;
}
};
int LinearSearch(Student* studentArray, int age)
{
for (int i = 1; i <= 14; i++)
{
cout << "DEBUG AGE: " << age << endl;
cout << "DEBUG: Searched student: " << i << " His age was: " << studentArray[i].age << endl;
if (studentArray[i].age = age)
{
return i;
}
}
return -1;
}
int main()
{
Student student[10];
string name;
string teacher;
int age;
int students;
cout << "Welcome, what's your name?: ";
cin >> teacher;
cout << "Welcome to your new job, " << teacher << ".\n\n";
cin.get();
cout << "As a new teacher, you will have to set up your class in this program.";
cin.get();
cout << "Note that you're only allowed to teach 14 students as max.";
cin.get();
cout << "How many students are you going to be teaching this semester?: ";
cin >> students;
int i;
for (i = 1; i <= students; i++)
{
cout << "Enter student name: ";
cin >> name;
cout << "Enter student age: ";
cin >> age;
student[i].store(name, age);
}
cout << "You have " << students << " students.\n";
cout << "Let's make sure they got put in correctly.\n";
cout << "Print student ID: ";
int input;
while (true)
{
cin >> input;
if (input <= students)
{
student[input].print();
break;
}
else
{
cout << "Error, student " << input << " does not exist. Please try again: ";
}
}
cout << "\nTime skips until after spring break...\n";
cin.get();
cout << "Welcome back, " << teacher << ".";
cin.get();
while (true)
{
cout << "\nWhat activity do you want to do today?\n";
cout << "1. Search information about a student (Linear)\n";
cout << "2. Search information about a student (Binary)\n";
cout << "3. Print class in order of age\n";
cout << "4. Quit\n";
cin >> input;
if (input == 1)
{
int search;
cout << "Student age: ";
cin >> age;
search = LinearSearch(student, age);
if (search = -1)
{
cout << "Error: There's no student by the age: " << age << endl;
}
else
{
cout << "The first match was: " << student[search].name;
cout << student[search].name << " is student number: " << search;
}
}
elseif (input == 4)
{
exit (EXIT_SUCCESS);
}
}
cin.sync();
cin.get();
return 0;
}