4

I'm having a problem with C++ programming language, please help me out. I'm writing a program that asks the user to enter a student ID and the program will extract the information of the student who has that ID from a list of 15 students in my .txt file. I have these lines of codes:

 void Person_list::changeName() { Person *s; string name; int id; int temp_id; s = head; cout << "Please enter student's ID: "; cin >> id; while ((s!=NULL) && (s -> getID() != id)) { s = s -> next; } if (s != NULL) { s -> Show(); } if (s == NULL) { cout << "Cant find" << endl; } } 

What I want to do is to ask the user to enter the students ID again (until the user enters an appropriate number) if the program can't find the student ID (for example when I enter 16, the program is not able to find a student because my list only contains 15 students). Any idea how to do this? thanks.

P/s I'm not allowed to use nullptr

4
  • 4
    I suggest to split your function and have a method Person *FindById(int id); and remove unused variables. Commented Sep 14, 2015 at 15:53
  • 2
    a do { /**/ } while (s == nullptr); may do the job. Commented Sep 14, 2015 at 15:54
  • You may not use nullptr. May you use NULL? They are two names for the same thing. Commented Sep 14, 2015 at 17:38
  • 1
    If your professor allows NULL, but disallows nullptr, then please replace the professor. Commented Sep 16, 2015 at 18:33

1 Answer 1

3

You may use something like:

Person* Person_list::FindById(int id) { for (Person* s = head; s != nullptr; s = s->next) { if (s->getID() == id) { return s; } } return nullptr; } void Person_list::changeName() { Person* s = nullptr; do { std::cout << "Please enter student's ID: "; int id; std::cin >> id; s = FindById(id); if (s == nullptr) { std::cout << "Cant find" << std::endl; } } while (s == nullptr); s->Show(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

the professor doesn't allow me to use nullptr unfortunately. Any other way guys? thanks
If you can't use nullptr, just compare pointers with 0 instead. By definition, a pointer with value zero is the null pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.