The search function should get a value from the user to search for it, if the value is found, then it should print it out, and if not found it should print not found.
However, in my code every time I write the number that is in the array is gives me the false option although it is in the array stored.
`
#include <iostream>
using namespace std;
const int size = 100;
int partsmenu(int menu_option);
void readparts(char part_number[][10], double price[], char classification[], int& number_of_parts);
int search(char part_number[][10], char search_target[], int number_of_parts, double price[], char classification []);
void display_parts(char part_number[][10], double price[], char classification[], int& number_of_parts);
int main()
{
const int size = 100;
int menu_option=0, option, displaysearch;
char part_number[size][10];
double price[size];
char classification[size];
int number_of_parts = 0;
char search_target[size];
//using switch statment to make it look like a menu option
do {
switch (option = partsmenu(menu_option))
{
case 1:
readparts(part_number, price, classification, number_of_parts);
break;
case 2:
display_parts(part_number, price, classification, number_of_parts);
break;
case 3:
displaysearch = search(part_number, search_target, number_of_parts, price, classification);
break;
case 4:
break;
default:
cout << "Not valid..." << endl;
break;
}
cout << endl;
} while (option != 4);
return 0;
}
int partsmenu(int menu_option)
{
cout <<"1) Enter new part number\n2) View all part numbers\n3) Search for part\n4) Exit\n\nEnter an option: ";
cin >> menu_option;
return menu_option;
}
void readparts(char part_number[][10], double price[], char classification[], int& number_of_parts)
{
// using for loop to store part number, price, and classification in the array
int number;
cout << "Enter number of parts to add:";
cin >> number;
cout << endl;
int i;
for (i = number_of_parts; i < (number_of_parts+number); i++)
{
cout << "Enter part number: ";
cin >> part_number[i];
cout << "Enter price: ";
cin >> price[i];
cout << "Enter classificarion: ";
cin >> classification[i];
//using if statment to check for the classificarion
if (classification[i] == 'A' || classification[i] == 'B' || classification[i] == 'C')
cout << "";
else
{
cout << "Invalid case..." << endl;
cout << "Enter Valid class [A, B, C]: ";
cin >> classification[i];
cout << endl;
}
cout << endl;
}
number_of_parts = i;
}
int search(char part_number[][10], char search_target[], int number_of_parts, double price[], char classification[])
{
//searching for specific data
bool found = false;
int value;
cout << "Enter part number: ";
for (int j = 0; j < number_of_parts; j++)
{
cin >> search_target;
for (int i = 0; i < number_of_parts && found == false; i++)
{
if (part_number[i] == search_target)
found = true;
value = i;
}
}
if (found == true)
{
for (int i = 0; i < number_of_parts; i++)
{
cout << "Part ID\t\tPrice\t\tClass" << endl;
cout << " --------------------------------------------" << endl;
cout << part_number[value] << "\t\t" <<price[value]<< "\t\t" <<classification[value]<< endl;
}
}
else
{
cout << "No parts found..." << endl;
value = -1;
}
return value;
}
void display_parts(char part_number[][10], double price[], char classification[], int& number_of_parts)
{
// displaying the data
cout << "Part ID\t\tPrice\t\tClass" << endl;
cout << "--------------------------------------------" << endl;
for (int i = 0; i < number_of_parts; i++)
{
cout << part_number[i] << "\t\t" << price[i] << "\t\t" << classification[i] << endl;
}
cout << endl;
}
`
I am trying to find what is wrong with code but could not find any fault with it. Everything else works fine.
You compare C strings with strcmp not ==. Like this
if (strcmp(part_number[i], search_target) == 0)
If you use == then all you are comparing is the addresses of the strings, the addresses of two strings can be different even if the string contents are the same.
strcmp compares the actual characters in the strings, not the addresses. It returns 0 if the two strings are the same.
Related
Hi I want to create a 2d growing dynamic array with use of char. The problem is that my function put all word in the same row. The dynamic allocation is not good but I don't know how to correct this.
void display(char** data, int length)
{
for (int i = 0; i < length; i++)
for (int j = 0; j < data[i][j] != '\0'; j++)
cout << data[i][j];
cout << endl;
}
void add(char** &data, int length, char* word)
{
if (length == 1)
{
data = new char* [length];
}
data[length-1] = new char[strlen(word)+1];
strcpy_s(*(data + length -1), strlen(word) + 1, word);
data[length - 1][strlen(word) + 1] = '\0';
}
int main()
{
char** data = NULL;
int choice = 0, length = 0; char name[80];
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); cin.getline(name, 80);
length++;
add(data, length, name);
break;
}
cout << endl << "Enter your next choice: " << endl;
}
This is what is get
Enter your choice
0
Enter name to add:
jhon
jhon
Enter your next choice:
0
Enter name to add:
marc
jhonmarc
I'm pretty sure that instead of
if (length = 1)
you meant to write
if (length == 1)
In C++ = means assignment and == means equality.
Seems your code has other bugs though. You never grow the size of data. Do it the easy way and use std::vector<std::string>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> data;
int choice = 0, length = 0; std::string name;
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); getline(cin, name); // read name
data.push_back(name); // add name to data
break;
}
cout << endl << "Enter your next choice: " << endl;
}
Problem solved.
This question already has answers here:
Using fstream Object as a Function Parameter
(3 answers)
Closed 6 years ago.
#include <bits/stdc++.h>
using namespace std;
class contact {
private:
vector< pair<string, int> > contact_info;
public:
void add_contact(string contact_name, int contact_number) {
contact_info.push_back(make_pair(contact_name, contact_number));
sort(contact_info.begin(),contact_info.end());
}
void edit_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
cout << "Enter the new number: ";
cin >> contact_info[found_at].second;
}
void show_all() {
for (unsigned int i =0; i < contact_info.size(); i++) {
cout << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void delete_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
for (unsigned int i =0; i < contact_info.size(); i++) {
contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void readFile(ifstream contact_file) {
string input;
while (!contact_file.eof()) {
contact_file >> input;
size_t pos = input.find(" ");
string name = input.substr(0,pos);
string number_str = input.substr(pos);
int number = stoi(number_str) ;
contact_info.push_back(make_pair(name,number));
}
}
};
int main()
{
int choice;
ifstream contacts_file_read;
contacts_file_read.open("contacts.txt");
ofstream contacts_file_write;
contacts_file_write.open("contacts.txt");
bool in_prog = true;
contact contacts;
string name;
int number;
while (in_prog) {
cout << "1. Add contacts" << endl
<< "2. Edit contact" << endl
<< "3. Delete contact" << endl
<< "4. Show all" << endl
<< "5. exit" << endl;
cout << "Your choice: ";
cin >> choice;
contacts.readFile(contacts_file_read);
if (choice == 1) {
cout << "Enter name & number separated by a space: ";
cin >> name >> number;
contacts.add_contact(name, number);
} else if (choice == 2) {
cout << "Enter name of contacts to be edited: ";
cin >> name;
contacts.edit_contact(name);
} else if (choice == 3) {
cout << "Enter name of contact to be deleted: ";
cin >> name;
contacts.delete_contact(name);
} else if (choice == 4) {
contacts.show_all();
} else if(choice == 5) {
contacts.writeFile(contacts_file_write);
} else {
cout << "Wrong choice" << endl;
}
}
return 0;
}
So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.
Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
// ^^^^^^^^^^
I've come across a little problem, how do I print the winning candidate's name? See the instructions here are, input five names, their number of votes and percentage of votes, whoever has the highest wins. I don't know if I did my code right, but it works.. well except for the name part. I've tried everything from a lot of for loops to transfer the array or what.
I'm almost done with the code.
Here's the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2f\n", percent[c]);
}
cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
printf("%.2f\n", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
You should keep a 2d array of characters or array of string for storing candidate names instead of a 1-d array.
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
Then keep a variable to store index for winning candidate
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
Finally print name of winning candidate;
cout << candidates[winIndex];
In object oriented approach, you may create a class with following information
class Candidate
{
string name;
int votes;
float percent;
};
Use string candidates[50]; instead of char candidates[50];
then cin >> candidates[a];
I have been having some trouble on my code for my final project. I have looked everwhere and I am having a hard time so I thought I would ask on here. I need to make sure that when all the names are listed in this phonebook that they will come out in alphabetical order but as of yet I am unsure how to do that. Here is the program that i currently have! Thank you!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct Contact {
string name, number, notes;
};
Contact contactList[100];
int rec_num = 0;
int num_entries;
string toUpper (string S) {
for (int i= 0; i < S.length(); i++)
S[i] = toupper(S[i]);
return S;
}
void ReadFile () {
string S;
fstream input("PhoneData.txt");
while (!input.eof() && !input.fail()){
input >> contactList[rec_num].name >> contactList[rec_num].number;
getline(input, S);
contactList[rec_num].notes = S;
rec_num++;
}
cout << "Book read." << endl;
num_entries = rec_num;
input.close();
return;
}
// stores phonebook for future runs of the program
void StoreFile () {
fstream F ("PhoneData.txt");
rec_num = 0;
while (rec_num < num_entries){
F << contactList[rec_num].name << " " << contactList[rec_num].number << " " << contactList[rec_num].notes << " " << endl;
rec_num++;
}
cout << "Phonebook stored." << endl;
return;
}
// adds contact
void add_name(string name, string number, string notes){
contactList[num_entries].name = name;
contactList[num_entries].number = number;
contactList[num_entries].notes = notes;
num_entries++;
return;
}
// finds contact
void retrieve_name(string name){
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
cout << "Phone Number: " << contactList[i].number << endl << "Notes: " << contactList[i].notes << endl;
return;
}
}
cout << "Name not found" << endl;
return;
}
// updates contact info
void update_name(string name){
string new_number;
string new_notes;
cout<<"New Phone Number"<<endl;
cin>> new_number;
cout<<"New Notes"<<endl;
cin>> new_notes;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
contactList[i].number = new_number;
contactList[i].notes = new_notes;
return;
}
}
}
// deletes contact
void delete_name(string name){
int INDEX=0;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
INDEX=i;
for ( int j=INDEX; j < num_entries; j++ ){
contactList[j].name = contactList[j+1].name;
contactList[j].number = contactList[j+1].number;
contactList[j].notes = contactList[j+1].notes;
}
}
}
return;
}
void listAllContacts() {
int i = 0;
while (i < num_entries) {
cout << "-- " << contactList[i].name << " " << contactList[i].number << endl << "-- " << contactList[i].notes << endl << endl;
i++;
}
}
int main(){
string name, number, notes;
string FileName;
char command;
FileName = "PhoneData.txt";
ReadFile ();
cout << "Use \"e\" for enter, \"f\" for find, \"l\" for list, \"d\" for delete, \"u\" for update, \"s\" for send message, \"q\" to quit." << endl << "Command: ";
cin >> command;
while (command != 'q'){
switch (command){
case 'e': cin >> name; cout << "Enter Number: ";
cin >> number; cout << "Enter Notes: ";
cin.ignore(); getline(cin, notes);
add_name(name, number, notes); break;
case 'f': cin >> name; retrieve_name(name); break;
case 'l':
listAllContacts(); break;
case 'u': cin>> name; update_name (name);break;
case 'd' : cin>> name; delete_name (name); break;
}
cout << "\nCommand: "; cin >> command;
}
StoreFile();
cout << "All set !";
return 0;
}
Given
Contact contactList[100];
int num_entries;
you can use std::sort to sort the list of contacts. std::sort has two forms. In the first form, you can use:
std::sort(contanctList, contactList+num_entries);
if you define operator< for Contact objects.
In the second form, you can use:
std::sort(contanctList, contactList+num_entries, myCompare);
if you define myCompare to be callable object that can compare two Contact objects.
To use the first form, change Contact to:
struct Contact {
string name, number, notes;
bool operator<(Contact const& rhs) const
{
return (this->name < rhs.name);
}
};
If you want to the comparison of names to be case insensitive, convert both names to either uppercase or lowercase and them compare them.
Prompt:
Convert the functions theSmallest() and fill_array()to template functions.
Test your template functions with 3 different data types: int, float and char.
Problem:
When I load this into the compiler, there are no errors. It works for INT and Float; however when I run the index_of_smallest function for the character option... it doesn't like it. When I actually check with a "cout" what the value for min is during a char call, it is giving me "-10002e89..". That value never changes so in the for loop the index_of_min is always 0 so the compiler thinks that the smallest character is always at the index of 0.
CODE:
#include <iostream>
#include <cstdlib>
using namespace std;
const int DECLARED_SIZE = 20;
template <class BaseType>
int index_of_smallest(BaseType a[], int size, int& number_used)
{
BaseType min = a[0];
int index_of_min = 0;
cout << index_of_min<< endl;
for (int index = 1 ; index < number_used; index++)
{
if (a[index] < min)
{
min = a[index];
index_of_min = index;
}
}
cout << index_of_min<< endl;
return index_of_min;
}
template <class BaseType>
void fill_array(BaseType a[], int size, int& number_used)
{
int index = 0;
BaseType ans;
cout << "Enter up to " << size << " of the Data Type selected.\n"
<< "Mark the end of a list of numbers with a negative number.\n"
<< "Mark the end of a list of characters with the negative symbol \"-\". \n"
<< "Separate each input with a space. \n" << endl;
cin >> ans;
while (ans >= 0 && ans != '-')
{
a[index] = ans;
index++;
cin >> ans;
}
number_used = index;
}
void menu()
{
int number_used, choice, smallest, result;
int start_index = 0;
char menuLoop = 'Y';
while (toupper(menuLoop) == 'Y')
{
cout << "Please select a type of Input: \n"
<< "1. Integers (1, 2, 3, 4, etc..)\n"
<< "2. Decimals (1.0, 2.0, 3.0. 4.0, etc..)\n"
<< "3. Characters ( a, b, c, d, etc...)\n\n\n";
cin >> choice;
switch (choice)
{
case 1:
int arrI[DECLARED_SIZE];
system ("CLS");
fill_array(arrI, DECLARED_SIZE, number_used);
smallest = index_of_smallest(arrI, start_index, number_used);
cout << "The smallest integer is: " << arrI[smallest] << " ";
break;
case 2:
float arrF[DECLARED_SIZE];
system ("CLS");
fill_array(arrF, DECLARED_SIZE, number_used);
smallest = index_of_smallest(arrF, start_index, number_used);
cout << "The smallest float is: "<< arrF[smallest] << " ";
break;
case 3:
char arrC[DECLARED_SIZE];
system ("CLS");
fill_array(arrC, DECLARED_SIZE, number_used);
smallest = index_of_smallest(arrF, start_index, result);
cout << "The smallest character is: " << arrC[smallest] <<" \n";
break;
default:
cout << "That is an invalid choice! Exiting Program";
}
cout << "\n\nWould you like to return to the main menu? (Y/N): ";
cin >> menuLoop;
while(toupper(menuLoop) != 'Y' && toupper(menuLoop) != 'N')
{
cout << "Invalid Choice: Please type (Y/N): ";
cin >> menuLoop;
}
system("CLS");
}
}
int main()
{
using namespace std;
menu();
system("PAUSE");
}
Your error is here:
smallest = index_of_smallest(arrF, start_index, result);
Which should be:
smallest = index_of_smallest(arrC, start_index, number_used);
You were using the wrong array, and you were passing result (which was never initialized) instead of number_used.