Hi.In the code below I need to create an array of structs that holds data about the patient's name and the hour of receipt.Then i have to search a patient using his name. I've done everything and the code works fine except there's something wrong at the IF statement in the Searching Section(commented in the code) and i can't figure out how to do it, cause everything i tried didn't work. When i input the last name from the list, it outputs "No such patient", and when i input a name from the middle, then it outputs " No such patient" and the data about that patient.
I have some questions about this code to someone who might answer the original question!
1. Since when can we create build in array using size that is not constexpr? (line 15)
2. What exactly struct means before struct patient patient1[n];
I always thought that it should be just type array_name[num_of_elements];
About your original question
1 2 3 4 5 6 7 8 9 10 11 12
for (int i=0;i<n;i++)
{
if (patient1[i].name==search)
{
cout <<"\nName: "<<patient1[i].name;
cout <<"\nHour: "<<patient1[i].hour;
break;
}
else
{
cout << " No such patient";
}
Every time element i is not the right one you are showing the message " No such patient". If there are 50 patients and the right one is last it will be printed 49 times and only in the last search you will get the name. Just remove else and create some bool variable that would indicate failure or success and only in case of failure you show the message "Not found" or take a look at std::find
The cstring is using the C style strings, but with a few modifications so that it works with C++.
This is some comments in my cstring file. Note that the C++ string class is a very different thing to a C string.
1 2 3 4 5 6 7 8 9
/** @file cstring
* This is a Standard C++ Library file. You should @c \#include this file
* in your programs, rather than any of the @a *.h implementation files.
*
* This is the C++ version of the Standard C Library header @c string.h,
* and its contents are (mostly) the same as that header, but are all
* contained in the namespace @c std (except for names which are defined
* as macros in C).
*/
With this:
1 2 3 4 5 6
int main()
{
int n;
cout << "Input the number of patients: ";
cin >> n;
struct patient patient1[n];
One can't do dynamic memory like that. Array sizes must be constant at compile time. Are you allowed to use std::vector by any chance?
As for the search-loop. The reason it's outputting the way it is, is because you've written the code that way. Consider this:
My list consists of 3 names. Ally, Bally and Shally.
If I search for Shally. Shally is not equal to Ally, so the first if statement will fail, and I will get "No such patient". Then It will search Shally Vs Bally, still not the same, if statement will fail and output no such patient, Now finally, we are at patient1[2] and it's sally vs sally. It will output the name and hour.