can't make strstr() work - c++

I have a homwework assignment that I can't get to work correctly at all in one area, specifically where I'm trying to compare strings.
Here is the assignment:
You will write a program that prompts the user for student names, ages, gpas, and graduation dates. Your program will then read in all the student information and store them into a linked list. The program will then print the names of the students. Next, the program will prompt the user for a string. The program will print the complete information for each student containing the string in the name.
Here's what I have:
#include <iostream>
#include <cstring>
using namespace std;
const char NAME_SIZE = 50;
struct StudentInfo
{
char studentName[NAME_SIZE];
int age;
double gpa;
char graduationSemester[3];
StudentInfo *next;
};
void displayStudentNames(StudentInfo *top);
void displayStudentInfo(StudentInfo *top);
int main(){
StudentInfo *top = 0;
cout << "Please enter the students. Enter the name, age, gpa, and semester of graduation (e.g. F13)." << endl;
cout << "Enter an empty name to stop." << endl << endl;
bool done = false;
while(!done){
char nameBuffer[NAME_SIZE];
char graduationBuffer[3];
cin.getline(nameBuffer, NAME_SIZE);
if(nameBuffer[0] != 0){
StudentInfo *temp = new StudentInfo;
strcpy(temp->studentName, nameBuffer);
cin >> temp->age;
cin >> temp->gpa;
cin.getline(graduationBuffer, 3);
strcpy(temp->graduationSemester, graduationBuffer);
cin.ignore(80, '\n');
temp->next = top;
top = temp;
}else{
displayStudentNames(top);
displayStudentInfo(top);
done = true;
}
}
}
void displayStudentNames(StudentInfo *top){
cout << "Here are the students that you entered: " << endl << endl;
while(top){
cout << top->studentName << endl;
top = top->next;
}
cout << endl;
}
void displayStudentInfo(StudentInfo *top){
char name[NAME_SIZE];
do{
cout << "Which students do you want? ";
cin.getline(name, NAME_SIZE);
const char *str = top->studentName;
const char *substr = name;
const char *index = str;
while((index = strstr(index,substr)) != NULL){
cout << "Name: " << top->studentName << ", Age: " << top->age << ", GPA: " << top->gpa << ", Graduations Date: " << top->graduationSemester;
index++;
}
}while(name[0] != 0);
}
My problem is happening in the displayStudentInfo function, I just can't make it work properly. I've tried many different things and this is just the latest thing I've tried. But after creating the linked list earlier in the program, we are supposed to enter a string ranging from a letter to a full name and find it anywhere in the list, then print out the information for that particular name.
eta: I'm also having a problem with my linked list storing the structures backwards? It also either isn't storing my graduation dates, or something's going wrong when I try to print them, because they print blank.

Your code problem is obvious. You are just checking head of list and not traversing into the list.
Here is a part that has problem(Assuming each function call should return info for 1 student):
void displayStudentInfo(StudentInfo *top){
char name[NAME_SIZE];
//Addes 'node' variable for simplicity, you can use 'top' itself
StudentInfo *node = top;
cout << "Which students do you want? ";
cin.getline(name, NAME_SIZE);
do{
// Check if name is correct
// "Entered name should be at start of field"
// You should use == not =
if(node->studentName == strstr(node->studentName, name){
cout << "Name: " << top->studentName << ", Age: " << top->age << ", GPA: " << top->gpa << ", Graduations Date: " << top->graduationSemester;
}
// Traverse in list
node = node->next;
// Until reach end of list
}while(node != NULL);
}

You need to add top = top->next somewhere inside displayStudentInfo, similarly to how you have done in displayStudentNames. Currently your loop does not iterate through the linked-list without this.
I won't post any code to avoid doing your homework, but feel free to ask me more questions or for clarification.

Related

i made c++ code where its need to pass structure pointer in a function

i got confused about the structure when i need to to pass the value in a function
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student(struct student *);
void display_student(struct student *);
int main()
{
student *s;
//struct student *ps;
read_student(s);
display_student(s);
}
void read_student(struct student *ps)
{
int i;
for (i = 0; i <= 2; i++)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
}
void display_student(struct student *ps)
{
int i;
cout << "student details :" << endl;
for (i = 0; i <= 2; i++)
{
cout << "student name : " << *ps ->studentName << " (" << &ps ->studentID << ")" << endl;
ps++;
}
}
its only problem at the variable at line 19 and when i try to edit it will became more problem
student *s;
//struct student *ps;
//struct student *ps;
read_student(s);
display_student(s);
also can someone explain how to transfer pointer value of structure to the function and return it back to the main function
You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work.
A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined behavior. For writing, it is the same, plus that the system will most likely crash.
So, define a student. And if you want to give it to a sub-function, take its address with th &-operator (this address will point to the student) and then it will work.
You need also to learn abaout dereferencing. Your output statement is wrong.
Last but not least, if you want to store 3 students, then you need an array or some other storage where to put them . . .
In your read function you always overwrite the previously read student and in your display function you show undetermined data.
Please have a look at your minimal corrected code:
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student( student*);
void display_student( student*);
int main()
{
student s;
//struct student *ps;
read_student(&s);
display_student(&s);
}
void read_student( student* ps)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
void display_student( student* ps)
{
cout << "student details :" << endl;
cout << "student name : " << ps->studentName << " (" << ps->studentID << ")" << endl;
ps++;
}
And, the commenters are right. You must read a book.

Linked List and inserting a string in alphabetical order

I'm writing a program that allows a user to insert, delete, search, and print books. The books must print out in alphabetical order. When I'm inserting books, it works just fine but it does not put them in the right order and it will crash. Here is my code for the insert function.
void BookList::Insert(Book* nBook)
{
string name;
int quant;
double p;
cout << "Enter the title of the book." << endl;
cin.ignore();
getline(cin, name);
cout << "Enter the number of quanities of this book." << endl;
cin >> quant;
cout << "Enter the price of this book." << endl;
cin.ignore();
cin >> p;
nBook->title = name;
nBook->quantity = quant;
nBook->price = p;
nBook->next = nullptr;
//cout << "test" << endl;
//If the current book is lexicographically smallest.
if (first == nullptr) {
first = nBook;
cout << first->title << endl;
}
else if (nBook->title <= first->title)
{
cout << "new first" << endl;
nBook->next = first;
first = nBook;
}
else
{
cout << first->title << endl;
//if current book is lexicographically small between two books.
Book* prevPtr = first;
while (prevPtr != nullptr)
{
cout << "Looking at: " << prevPtr->title << endl;
if (prevPtr->title > nBook->title)
{
break;
}
else
{
prevPtr = prevPtr->next;
}
}
nBook->next = prevPtr->next;
prevPtr->next = nBook;
}
}
P.S. This is in C++
Thank you
Just because something doesn't show an error at compile doesn't mean it works fine.
Why are you using cin.ignore() with no parameters? What is the single character you are trying to ignore? You realize cin >> (someint or somedouble) already ignores whitespace and return characters, right?
More of your code is needed for context, but it seems like you're trying to fill the information for the new book into a "nBook" node before you actually initialize a new "nBook" node.
Also, I suggest not putting that output at the end in the method. If your method is for adding a new book to your linklist, just use it to add it. Put those outputs in a separate method, or in the calling method. (or maybe you just put those in for debugging purposes, in which case nvm)
Just my 0.02

Calling for function, only returning 0

Alrighty, the goal of what I am trying to do right now is call the function getSingleStudentInfo, which contains the student's number, last name, and age. In the end this program is designed to do two things, the first being the single student info, the second, printing out an array of 20 students. Disregard the second part, as I have not really gotten into that part yet, so ignore anything involving vectors.
The problem that I am having is that in main the first thing that the program will do is ask you to press 1 for the single info or 2 for the full 20 peoples info. The program compiles fine, but what happens is, no matter what number you enter, the program will say "process returned 0 (0x0)" and be done, I'm having a hard time figuring out why it is doing that instead of printing out the single students info, being "student's ID number is 400" "student's last name is: Simmons" "student's age is: 20"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
cout << "Student's ID number is: ";
cout << s.studentNumber << endl;
cout << "Student's last name is: ";
cout << s.lastName << endl;
cout << "Student's age is: ";
cout << s.age << endl;
return;
};
int main()
{
cout << "Press '1' to see a single student data entry" << endl;
cout << "Press '2' to see all 20 student records" << endl;
cin >> selection;
if (selection == 1) {
getSingleStudentInfo;
};
/*for (vector<int>::size_type i = 0; i <= 20; i++)
{
cout << "Student's ID number is: " << 400 + i << endl;
}
return 0;*/
}
You need to call the function, e.g.
if (selection == 1)
{
getSingleStudentInfo(7, "Johnson", 20);
}
However, it seems like by the implementation, this should be a method off of the student itself
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
void getSingleStudentInfo() const;
};
Then you'd call it off a Student instance
Student s{400, "Simmons", 20};
s.getSingleStudentInfo();
Then if you had a vector of Student you could do
std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
end(students),
[](const Student& s){s.getSingleStudentInfo();});
To print in columns, you could change your function to something like
void Student::getSingleStudentInfo()
{
cout << s.studentNumber << '\t'
<< s.lastName << '\t'
<< s.age << endl;
};

C++ function in switch statement is not executing

I'm new to c++ and I'm trying to make a simple class roster program that accepts new students storing the student data in an array that then be sorted and display the contents of the array. However when running the program and entering the menu selection, two of the three functions do not work. Any help or guidance is much appreciated. My code is here.
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
//Create Students class
class Students
{
public:
char sFirstName[256];
char sLastName[256];
int sStudentID;
double sGrade;
double sGPA;
double nCreditHours;
};
//functions
Students addStudent();
//void displayRoster();
//void sortRoster();
void showMenu();
void showWelcome();
//Welcome function
void showWelcome()
{
cout << "Welcome to my class roster program. \n"
<< "This program can be used to add students to the roster, \n"
<< "which can then be sorted by either name or I.D. number. \n"
<< endl;
}
//Menu function
void showMenu()
{
cout << " Student Roster: \n"
<< "MAIN MENU PLEASE SELECT AN OPTION" << endl;
cout << "1) Add student to roster: " << endl;
cout << "2) Display current roster: " << endl;
cout << "3) Sort roster: " << endl;
cout << "4) Exit program: " << endl;
//cout << "5) Display roster sorted by 'student I.D.': " << endl;
//cout << "6) Display roster sorted by 'Grade': " << endl;
//cout << "7) Display roster sorted by 'GPA': \n" << endl;
cout << " Make your selection: \n" << endl;
}
//Add student function
Students addStudent()
{
Students student;
cout << "Add student to roster. \n"
<< "Enter first name: " << endl;
cin >> student.sFirstName;
cout << "Enter last name: " << endl;
cin >> student.sLastName;
cout << "Enter student I.D.: " << endl;
cin >> student.sStudentID;
return student;
}
void displayStudent(Students student)
{
cout << "Student name: " << student.sFirstName << " "
<< student.sLastName << endl;
cout << "I.D. # " << student.sStudentID << endl;
}
void displayRoster()
{
Students student[256];
int nCount;
for (int index = 0; index < nCount; index++)
{
displayStudent(student[index]);
}
}
int getStudents(Students student[], int nMaxSize)
{
int index;
for (index = 0; index < nMaxSize; index++)
{
char uInput;
cout << "Enter another student to the roster? (Y/N): ";
cin >> uInput;
if (uInput != 'y' && uInput != 'Y')
{
break;
}
student[index] = addStudent();
}
return index;
}
void sortRoster()
{
Students student[256];
int nCount;
//bubble swap
int nSwaps = 1;
while (nSwaps != 0)
{
nSwaps = 0;
for (int n = 0; n < (nCount - 1); n++)
{
if (student[n].sStudentID > student[n+1].sStudentID)
{
Students temp = student[n+1];
student[n+1] = student[n];
student[n] = temp;
nSwaps++;
}
}
}
}
int main()
{
int selection; //menu selection variable
//constants for menu selection
const int ADD_STUDENT = 1,
DISPLAY_ROSTER = 2,
SORT_ROSTER = 3,
QUIT_PROGRAM = 4;
Students student[256];
//int nCount = getStudents(student, 256);
do
{
showWelcome(); //Show welcome message
showMenu(); //Show menu options
cin >> selection;
while (selection < ADD_STUDENT || selection > QUIT_PROGRAM)
{
cout << "Enter a valid selection: ";
cin >> selection;
}
if (selection != QUIT_PROGRAM)
{
switch (selection)
{
case ADD_STUDENT:
addStudent();
break;
case DISPLAY_ROSTER:
displayRoster();
break;
case SORT_ROSTER:
sortRoster();
break;
}
}
}
while (selection != QUIT_PROGRAM);
return 0;
}
The problem is not in the switch.
The addStudent() is not adding the student into any list or array. Also since it return type is Students you should add it into the any array of Students. Since you have not stored any data display won't display anything.
The another problem is of nCount. You are using it in for comparison without initializing it. Also to keep nCount synchronized either make it global, use as pointer or handle it with return.
Also the problem is in displayRoster(). You are declaring Students array as Students student[256]; and you are using it without initializing. Also if initialized, it won't have the data which was given as input.
NOTE: Sit and read your code again, there are many more mistakes. Try visualizing how your data should be stored and how your code is to behave and then start writing code.
Your nCount is not initialised. Since this variable is used in those two functions (and assuming that it refers to the total count), you can declare it as a global variable:
nCount=0;
Everytime you add a new entry, you can increment the counter as:
nCount++;
Another suggestion to make your code actually work:
student[i++]=addStudent();
where i is a counter initialised to 0. Your addStudent() function returns an object, and you discard it. Store it in the array of objects you created:
Students student[256];
Also, since you use the above in almost all functions, it is best to declare it as global rather than redeclaring in each function.

Sorting names between a Student class

edit. I want to thank the two people who helped me in my code. I fixed my coding as of 7:22 PM PST 9/25/2014. Still having trouble with the sorting though.
So I'm trying to teach myself how to use C++ in order to get ahead of my programming class in school. I've already taken Java so I'm relatively familiar with the structure of the coding but not exactly sure what to be typing. This practice problem is:
1)Ask the user how many people he wants to enter into the list.
2)Read 3 strings, then turn that info into a student class and put the student inside a vector.
3)Sort the list by name. (Extra credit would be to sort the list by Student ID)
4)Print the info of each student in the list.
5)Ask user while answer is 'Y', search the list for a name and print the info correlating to the name
While in Java, this seems pretty easy, I'm having an extremely hard time understanding what is going on in C++.
I currently only have 1, 2, 4 and 5 done. This is what I have so far.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
class Student
{
string myName, myStudentID, myClassID;
public:
Student(string name, string studentID, string classID)
{
myName = name;
myStudentID = studentID;
myClassID = classID;
}
string getName() { return myName; }
string getStudentID() { return myStudentID; }
void printInfo() { cout << myName << setw(15) << myStudentID << setw(10) << myClassID << endl; }
};
int main()
{
int num;
std::vector<Student> studentList;
cout << "How many students do you wish to add to the student list ? " << endl;
cin >> num;
cin.ignore();
for (int a = 0; a < num; a++)
{
string inputName, inputStudentID, inputClassID;
//get name
cout << "Please enter the Student name : ";
getline(cin, inputName);
//get student ID
cout << "Please enter the Student ID number : ";
getline(cin, inputStudentID);
//get class ID
cout << "Please enter the Student class ID : ";
getline(cin, inputClassID);
Student thisStudent(inputName, inputStudentID, inputClassID);
studentList.push_back(thisStudent);
cout << endl;
}
//sort(studentList.begin(), studentList.end());
/*
I never figured out how to sort the list by name.
I do not know how to compare the name of studentList[0] and studentList[1]
to put them in alphabetical order.
*/
cout << endl;; // FORMATTING
cout << "The student list has a size of " << studentList.size() << endl;
cout << endl;; // FORMATTING
cout << "Student Name" << setw(15) << "Student ID" << setw(10) << "Class ID" << endl;
for (int a = 0; a < studentList.size(); a++)
{
studentList[a].printInfo();
}
cout << endl;; // FORMATTING
string searchedName;
char answer;
do
{
cout << endl;; // FORMATTING
cout << "Please type the name of the person you want to search for: ";
getline(cin, searchedName);
for (int a = 0; a < studentList.size(); a++)
{
if (searchedName.compare(studentList[a].getName()) == 0)
{
studentList[a].printInfo();
break;
}
else
if (a == (studentList.size() - 1)) //If went to end of the list, tell them name not found.
cout << "There is no " << searchedName << " in the list. \n";
}
cout << "Would you like to search for another person? \n";
cout << "Y for Yes, N for No. \n";
cin >> answer;
cin.ignore();
} while (answer == 'Y' || answer == 'y');
return 0;
}
You could create a static compare function in class Student to use with std::sort
class Student
{
string myName, myStudentID, myClassID;
// ...
static bool compare_name(const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);}
};
// ...
std::sort(studentList.begin(), studentList.end(), Student::compare_name);
or if your compiler supports lambda functions:
std::sort(studentList.begin(), studentList.end(),
[studentList](const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);});