C++ String Array search outputs for every item - c++

I know it's somewhat confusing this title of question but I really need help.
I need to find a string in array with many strings. If the string is not found then the appropriate message is showed. However when I use for loop, it then shows this message for every string in array which is not found although it also shows found string... I hope you understand what I mean and sorry if i'm not making sense. here's my code:
void Store::search() {
string name;
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
for (int i = 0; i < quantity; i++) {
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
}
else
{
cout << "Product doesn't exist in database!" << endl;
}
}
}
The code works for searching but how do I stop the output "Product doesn't exist in database!" for every item in array that is not found(even when searched item is found)?
Thank You in advance

You can use statement flag:
void Store::search()
{
string name;
bool found = false
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
for (int i = 0; i < quantity; i++)
{
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true;
break;
}
if (!found)
cout << "Product doesn't exist in database!" << endl;
}

You can also use std::find_if, which will make your code look something like:
auto it = std::find_if(databases.begin(), databases.end(), [&name](const auto &database) {return name.compare(database.name) == 0; });
if (it != databases.end())
{
cout << it->name << endl;
cout << "found" << endl;
}
else
{
cout << "not found" << endl;
}
Generally speaking, C++ offers many such features that more often than not will make your code shorter, improve readability and guarantee functionality

You can:
1. keep a bool variable to be set to true if the item is found in the for loop
2. add a break to immediately exit for loop when item is found
3. remove the else part, because it will print out "Product doesn't exist in database!" for each loop cycle if the item does not match
4. after the for loop, check if found is false to check if item does not exist in collection
bool found = false;
for (int i = 0; i < quantity; i++)
{
if (name.compare(database[i].name) == 0)
{
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true; // set "found" to true
break; // add a break to immediately exit for loop when item is found
}
}
if (!found)
{
cout << "Product doesn't exist in database!" << endl;
}

I assume you want to search a product in the database and print its details if found. Otherwise you want to notify user that the product was not found. If I understood you correctly, then you need to move the else statement out of 'for' loop, e.g.:
void Store::search() {
string name;
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
bool found = false;
for (int i = 0; i < quantity; i++) {
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true;
break;
}
}
if (!found)
{
cout << "Product doesn't exist in database!" << endl;
}
}
If your database may contain more products with the same name, remove 'break;' statement.

A more "modern C++" approach is to leverage the C++ algorithms (such as std::find_if), lambdas and maybe the auto specifier.
As example (assuming database is a std::vector or some kind of STL container):
auto it = std::find_if(database.begin(), database.end(), [&name](const auto& item) { return name.compare(item.name) == 0; });
if (it != database.end())
{
cout << it->name << endl;
cout << "found" << endl;
}
else
{
cout << "not found" << endl;
}

Related

i am trying to display employees based on their designation like hr,developer like that i tried a code but it is not displaying output

iam trying to display employees based on their designation like hr,developer like that i tried a code but it is not displaying output
void searchDeptReport()
{
system("cls");
char department[20];
int i;
;
bool found = false;
cout << "\nYou can Search only through the designation of Employees\n\n";
cout << "\nEnter the Department to get report : ";
cin >> department;
for (int i = 0; i <= num - 1; i++)
{
if (emp[i].designation == department)
{
cout << "\nName\t Emp ID\tGender\t Designation " << endl;
cout << "------------------------------------------------\n";
gotoXY(0, 7);
cout << "Name : " << emp[i].name << endl;
gotoXY(11, 7);
cout << "Employee Id : " << emp[i].code << endl;
gotoXY(21, 7);
cout << "Gender : " << emp[i].gender << endl;
gotoXY(35, 7);
cout << "Designation : " << emp[i].designation << endl;
found = true;
cout << "\n\nPress Any key for Menu..";
}
}
if (!found)
{
cout << "\n\nNo records Found...!!!\a";
cout << "\n\nPress Any key for Menu..";
}
getch();
}
enter image description here

Searching for an Integer in an Output File C++

I'm currently writing a menu driven program in C++ and I'm having a little difficulty searching for a certain int in an Output file. My function looks like this.
int studentId;
int searchId;
double examGrade1, examGrade2, examGrade3;
ifstream readGrades;
do
{
cout << "Enter the student ID: ";
cin >> searchId;
if (searchId < 0 || searchId > 9999) {
cout << "Your student ID must be in between 0 and 9999! Try again...\n";
}
} while (searchId < 0 || searchId > 9999);
readGrades.open("grades.txt");
if (readGrades)
{
system("cls");
while (readGrades >> studentId >> examGrade1 >> examGrade2 >> examGrade3)
{
if (searchId == studentId)
{
cout << left
<< "Student ID\t" << "Exam 1\t" << "Exam 2\t" << "Exam 3\t" << endl;
cout << "======================================" << endl;
cout << left << setw(4) << studentId << "\t\t"
<< fixed << setprecision(2)
<< left << setw(5) << examGrade1 << "\t"
<< left << setw(5) << examGrade2 << "\t"
<< left << setw(5) << examGrade3 << endl;
system("pause");
break;
}
else
cout << "Entered ID not found";
}
}
else
{
cout << "Error opening file!\n";
}
cout << endl; }
Now the problem is the else statement. I am supposed to prompt to the user that a certain ID doesn't exist. But I don't know how to make the else statement only run once in the while statement. Every time I search a non-existing ID, it will say "Entered ID not found" for however many times it reads the inputs.
So the results look something like this.
No ID Found
At the same time, if I enter an ID that does exist but it's third in the file, it will look something like this. ID Found
I know logically what is happening, it keeps running the while loop for however many times. But I don't know how to deal with the problem. Any help to lead me to the right direction would be helpful. I'm new to coding/C++ and not too familiar with searching for something inside a file. Thank you!
The else block is in the wrong place. You need to update your logic such that you print that message only if the student ID is not found after going through the entire file. Which means, it has be outside the while loop.
if (readGrades)
{
bool found = false;
while (readGrades >> studentId >> examGrade1 >> examGrade2 >> examGrade3)
{
if (searchId == studentId)
{
cout << left
<< "Student ID\t" << "Exam 1\t" << "Exam 2\t" << "Exam 3\t" << endl;
cout << "======================================" << endl;
cout << left << setw(4) << studentId << "\t\t"
<< fixed << setprecision(2)
<< left << setw(5) << examGrade1 << "\t"
<< left << setw(5) << examGrade2 << "\t"
<< left << setw(5) << examGrade3 << endl;
found = true;
break;
}
}
if ( !found )
{
cout << "Entered ID not found";
}
}

C++ - Assigning character values to a string in a vector using range based for loop doesn't assign the value

I'm working on a self-imposed practice exercise. The parameters are that I allow the user to enter a name that is stored in a vector. Printing the list of names in the vector gives you the position of each name. You can choose to encrypt a name in the list by providing the name's position. Encryption compares each letter in the name with another string that is the allowed alphabet for names. When it finds the letter in the alphabet, it pulls a corresponding character from another string of random characters and assigns the new character to the same position.
Using a range based for loop I almost got it to work. By adding output statements I can see the code correctly comparing the characters of a name to the allowed alphabet and finding the corresponding value in the encryption key. However when the loop is complete and I print the list of names again, the characters in the name to be encrypted are unchanged.
Trying to troubleshoot the issue, I have commented out the range based for loop and tried to do the same thing with a traditional for loop. With this code I get and error during encryption:
Position 1 A is the same as #
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 26) >= this->size() (which is 2)
The "Position 1 A is the same as #" line is a debug output that I added to show that the code is able to find the correct string, a letter in the string, and the corresponding letter in they key.
Any help in understanding why I get those errors would be appreciated.
Here's my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
// Declare strings for Encryption and Decryption
string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "};
string key {"mnbvfghytcqwi1234567890`~!##$%^&*()-=_+[]\{}|;':,./<>?"};
//Declare collection of names for the list
vector <string> names {};
//Declare character to hold the user menu selection
char selection {};
string user_input{};
string banner (50, '=');
//Print menu
do
{
cout << "\n" << banner << endl;
cout << "A - Add name to list" << endl;
cout << "P - Print all names in list" << endl;
cout << "E - Encrypt a name in the list" << endl;
cout << "D - Decrypt a name in the list" << endl;
cout << "S - Show details of a name in the list" << endl;
cout << "C - Clear all names in the list" << endl;
cout << "Q - Quit" << endl;
cout << banner << endl;
cout << "Selection: ";
getline(cin, user_input);
if (user_input.size() != 1)
{
cout << "Error 4: Menu selection must be a single character" << endl;
selection = '1';
}
else
{
for (auto c: user_input)
{
if (!isalpha(c))
{
cout << "Error 5: Menu selection must be an alphabetic character" << endl;
selection = '1';
}
else
selection = c;
}
}
// cin >> selection;
// cin.clear();
// cin.sync();
switch (selection)
{
case 'a':
case 'A':
{
string temp_name{};
bool invalid_name {false};
cout << "Enter full name: ";
getline(cin, temp_name);
if (!isalpha(temp_name[0]))
cout << "Error 2: Names must begin with an alphabetic character" << endl << endl;
else
{
for (auto c: temp_name)
{
if (!isalpha(c) && !isspace(c) && c != '-')
{
invalid_name = true;
break;
}
else
invalid_name = false;
}
if (invalid_name)
cout << "Error 3: Name contains invalid characters" << endl << endl;
else
{
temp_name.at(0) = toupper (temp_name.at(0));
for (size_t i {1}; i < temp_name.size(); i++)
{
size_t position{i-1};
if (isspace(temp_name.at(position)) || temp_name.at(position) == '-')
{
temp_name.at(i) = toupper(temp_name.at(i));
}
}
names.push_back(temp_name);
cout << "Added name #" << names.size() << endl;
}
}
break;
}
case 'p':
case 'P':
{
for (size_t i {0}; i < names.size(); i++)
cout << i+1 << ". " << names.at(i) << endl;
break;
}
case 'e':
case 'E':
{
size_t encrypt_input{}, key_position{}, name_position {}, name_size {};
cout << "Enter the position of the name to encrypt: ";
cin >> encrypt_input;
cin.clear();
cin.sync();
if (encrypt_input < 1 || encrypt_input > names.size())
cout << "Error 6: Invalid selection for name to encrypt" << endl << endl;
else
{
name_position = encrypt_input - 1;
name_size = names.at(name_position).size();
cout << "Encrypting name: " << names.at(name_position) << " of size " << name_size << endl << endl;
cout << "Position 1 " << names.at(name_position).at(0) << " is the same as ";
key_position = alphabet.find(names.at(name_position).at(0));
cout << key.at(key_position) << endl;
for (size_t i {0}; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(key_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(key_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
/*
for (auto c: names.at(encrypt_input-1))
{
cout << "Converting " << c << " to ";
key_position = alphabet.find(c);
cout << key.at(key_position) << endl;
c = key.at(key_position);
cout << "C is now " << c << endl << endl;
}
*/
}
cout << names.at(encrypt_input-1) << endl;
break;
}
case 'q':
case 'Q':
cout << "Goodbye" << endl << endl;
break;
default:
cout << "Error 1: Invalid menu selection" << endl << endl;
break;
}
} while (selection != 'Q' && selection != 'q');
return 0;
}
Welcome to Stackoverflow! I agree entirely with PaulMcKenzie that such a big function is not the best for a variety of reasons - the immediate reasons are that its hard to read and hard to find problems - but there are more reasons as well.
Having said that you have a bug that I can see in the E case.
for (size_t i {0}; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(key_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(key_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
Should be
for (unsigned int i{ 0 }; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(name_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(name_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
ie key_position should be name_position in 2 places.
There may be other bugs, but this should stop the crashing and do the encoding right.
EDIT: On request of OP have added a new code fragment.
int i = 0; // position counter
for (auto c: names.at(encrypt_input-1))
{
cout << "Converting " << c << " to ";
key_position = alphabet.find(c);
cout << key.at(key_position) << endl;
c = key.at(key_position);
cout << "C is now " << c << endl << endl;
names.at(name_position).at(i++) = c; // update the names variable.
}
This should solve the problem you mentioned for the auto loop.
You're accessing an invalid location of names vector and the error / exception is showing that.
When you do this:
names.at( key_position ).at( i )
// ^^^
// It should be name_position
in this statement,
cout << "Finding " << names.at( key_position ).at( i ) << " in key at position " << key_position << endl;
you're accessing an invalid index of names whereas it should be:
names.at( name_position ).at( i )
and, that'll work because it access a valid index.
You're making the same mistake in this statement as well:
cout << "Changing " << names.at( key_position ).at( i ) << " to " << key.at( key_position ) << endl;
Correct these and it should work!
Tip:
It's time you read How to debug small programs.
It'll help you figure out what's wrong with your program in a more systematic way.
A few points regarding your code organization in general:
You should divide your program in functions instead of cluttering the main function.
You may write functions corresponding to each of your case in switch statement e.g. addName(), encryptName(), decryptName(), etc.
This modularity will definitely help you and other people to read, debug, maintain and extend your code easily and efficiently. In your case, it would also help you write an Minimal, Complete, and Verifiable example in no time.
Hope that helps!
Best of luck!
Happy coding!

How to successfully write to a .DAT file contents in a vector using C++?

I'm trying to write to a .DAT file my list of saved patients that are stored in a vector named PatientsInSystem. However, it won't work for some reason. Does anyone know what I might be doing wrong?
if (!PatientsInSystem.empty()) {
cout << "Error. There are still patients checked in. They must be checked out before quitting." << endl;
cout << "Printing remaining patients in the system... " << endl;
for (int i = 0; i < PatientsInSystem.size(); i++) {
cout << "Patient's ID: " << PatientsInSystem.at(i)->getID() << endl;
cout << "Patient's Name: " << PatientsInSystem.at(i)->getFirstName() << " " << PatientsInSystem.at(i)->getLastName() << endl;
cout << "Patient's Birthday: " << PatientsInSystem.at(i)->getBirthDate() << endl;
cout << "Patient's Primary Doctor's ID: " << PatientsInSystem.at(i)->getPrimaryDoctorID() << endl;
}
}
else {
outFile.open("CurrentPatients.dat", ios::out | ios::binary);
if (!outFile.is_open()) {
cout << "File not open." << endl;
}
else {
cout << "Binary file open, saving patients now...\n";
cout << "----------------------------------------\n";
for (int i = 0; i < PatientsInSystem.size(); i++) {
Patient * p;
p = PatientsInSystem.at(i);
outFile.write(reinterpret_cast<char *> (&p), sizeof(p));
}
}
outFile.close();
[This next section of code is the same as above only edited after the first amount of help received]
Here is the edited version of the code...
PatientList is my temporary vector which must be emptied for PatientsInSystem vector to write to the file
case 'q': {
if (!PatientList.empty()) {
cout << "Error. There are still patients checked in. They must be checked out before quitting." << endl;
cout << "Printing remaining patients in the system... " << endl;
for (int i = 0; i < PatientList.size(); i++) {
cout << "Patient's ID: " << PatientList.at(i)->getID() << endl;
cout << "Patient's Name: " << PatientList.at(i)->getFirstName() << " " << PatientList.at(i)->getLastName() << endl;
cout << "Patient's Birthday: " << PatientList.at(i)->getBirthDate() << endl;
cout << "Patient's Primary Doctor's ID: " << PatientList.at(i)->getPrimaryDoctorID() << endl;
}
}
else {
outFile.open("CurrentPatients.dat", ios::out | ios::binary);
if (!outFile.is_open()) {
cout << "File not open." << endl;
}
else {
cout << "Binary file open, saving patients now...\n";
cout << "----------------------------------------\n";
for (int i = 0; i < PatientsInSystem.size(); i++) {
outFile.write(reinterpret_cast<char *> (PatientsInSystem.at(i)), sizeof(Patient));
}
}
outFile.close();
Is there a reason you are using an array of pointers vs a flat array of structs?
You are writing the local pointer variable p, instead of the Patient data. You would just pass p instead of &p (or just pass .at() directly), and the bytes parameter should be sizeof(Patient).
If these are pointers to different sized derived classes, this has issues.
Also, the loop won't every be entered, because its in the block entered when .empty() is true.

C++ Hangman Game, how to make "right" letter stick

I am trying to do a hangman project, but my code isn't working. Whenever I put in the proper letter, the code tells me it is wrong (even though it is right). Not really sure why - the code worked at some point but I changed some things and now I don't know why it doesn't work. So it is probably a simple fix, but I am just not seeing it.
Any help would be very appreciated!
#include <iostream>
using namespace std;
int letterFill (char, string, string&);
int main()
{
string name;
int maxAttempts = 5;
int wrongGuesses;
char letter;
srand(time(0));
const string wordList[15] = { "hanukkah", "sparklers", "mistletoe", "menorah", "presents", "reindeer",
"kwanzaa", "snowman", "eggnog", "celebration", "yuletide", "resolution", "nutcracker", "ornaments", "gingerbread" };
string correctWord = wordList[rand() % 15];
string unknown(correctWord.length(),'*');
cout << correctWord << endl;
cout << "Welcome to a fun game of winter holiday hangman! What is your name? " << endl;
cin >> name;
cout << name <<", there are some simple things you should know about this game before you start playing!" << endl;
cout << "You will be trying to guess a randomly selected word by typing in ONE letter at a time " << endl;
cout << "You will have " << maxAttempts << " tries before losing the game " << endl;
cout << "And remember, all of the words are winter holiday related. Good luck " << name <<"!" << endl;
cout << "*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*" <<endl;
while (wrongGuesses == 0)
{
cout << "Guess a letter" << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 1)
{
cout << "You have 4 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 2)
{
cout << "You have 3 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 3)
{
cout << "You have 2 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 4)
{
cout << "You have 1 guess left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 5)
{
cout << "Sorry " << name << " you have made 5 wrong guesses!" << endl;
cout << "Game over. Click any key to exit. Play again soon :) " << endl;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
system("pause");
return 0;
}
int letterFill (char guessLetter, string mysteryWord, string& guessWord)
{
int x;
int matches=0;
int lengthWord=mysteryWord.length();
for (x = 0; x< lengthWord; x++)
{
if (guessLetter == mysteryWord[x])
return 0;
if (guessLetter == mysteryWord[x])
{
guessWord[x] = guessLetter;
matches++;
}
}
return matches;
}
You aren't updating the string guessWord in your int letterFill() function. As soon as you see a letter that matches you return without entering that second if statement.
I assume what you want is only to return after fully updating the guessWord, based on that what you want to do is iterate through the string, updating guessWord as you find matches and after your loop do a check
if(matches == 0) return 0;
else return matches;