Ok I searched for questions but couldn't get my answer, or was not using appropriate term.
if(choice == 2){
string tempName, tempAddress; int tempNic,tempContact;
cout << "\n\t\t*\tWelcome to Our Sponsor Registeration Section\t*\n\n";
cout << "Please enter your name : "; cin>>tempName;
cout << "Please enter your National Identity Card Number : "; cin>>tempNic;
cout << "Please enter your Contact Number : "; cin>>tempContact;
cout << "Please enter your Address : "; cin>>tempAddress;
// prototype Sponsor(string n, string add, int nic_n, int phone) constructor
Sponsor (Constructor goes here) // how to make many objects now?
}
the code is pasted here https://codeshare.io/aVxl42
check line 69 where i am going to use a constructor to add the values, by this i can add 1 object, but what shall i do such that if a person who is using program wants to add more objects do it?
I know i need to encapsulate something between 61 and 70.
Please help me how i work this out.
I'm guessing you want to make it loop? I'd suggest a while-loop.
I haven't used vectors in forever(professors forbid it) so I may make some mistake, but you'll get the overall point.
bool stop = false; //This is to check after each loop if it should continue or not
char contChoice;
vector<Sponsor> sponsors;
while(!stop){
if(choice == 2){
string tempName, tempAddress; int tempNic,tempContact;
cout << "\n\t\t*\tWelcome to Our Sponsor Registeration Section\t*\n\n";
cout << "Please enter your name : "; cin>>tempName;
cout << "Please enter your National Identity Card Number : "; cin>>tempNic;
cout << "Please enter your Contact Number : "; cin>>tempContact;
cout << "Please enter your Address : "; cin>>tempAddress;
// prototype Sponsor(string n, string add, int nic_n, int phone) constructor
sponsors.push_back(Sponsor(tempName, tempAddress, tempContact, tempNic));
//Add whatever other arguments you want to pass in, in whatever order
cout << "Do you want to continue? [Y/N]: "; cin>>contChoice;
if(contChoice == 'N' || contChoice == 'n')
stop = true;
else stop = false; //This isn't really necessary since it is false by default
}
}
But I would also suggest that you make set-member functions in Sponsor at least. You can also use a dynamic array and make it expand, which is trickier than a vector, way trickier in fact.
Related
I am currently working on a very simple project and I found a problem in the testing phase when I tried to enter his name for the new employee and the decision condition was suddenly triggered, I am not sure why this happened. Based on my limited coding experience, in general, a statement in an output judgment statement needs to fulfil a judgment condition, but why would a judgment condition be triggered if I didn't do any input? Thank you all for your help.
Here is a part of the code.
void Management::Add_Staff() {
std::cout << "Please enter the number of staffs you want to add: " << std::endl;
int addNum = 0; // saves the amount entered by the user
std::cin >> addNum;
while (addNum <= 0 || addNum >= 50) {
std::cout << "Invaild number. Please try again" << std::endl;
std::cout << "Please enter the number of staffs you want to add: " << std::endl;
std::cin.clear(); // clear error enter
std::cin.ignore(INT_MAX, '\n'); // INT_MAX means an extremely large number,'\n' means empty space
std::cin >> addNum;
}
int new_Size = this->_StaffNumber + addNum; // The number of existing employees plus
// the number of new employees
Person** new_Space = new Person*[new_Size]; // Open up new space
if (this->_StaffArray !=
NULL) // if the data of the original pointer is not null
{
for (int i = 0; i < this->_StaffNumber;
i++) // data of the original pointer is added to the new pointer
{
new_Space[i] = this->_StaffArray[i];
}
}
for (int i = 0; i < addNum; i++) {
int ID; // create an variable nameed id to store the staff number entered
// from users
std::cout << "Please enter pure and positive number as the staff number of " << i + 1 << " staff: " << std::endl;
std::cin >> ID;
while (ID <= 0) {
std::cout << "Invalid staff number, please enter again: " << std::endl;
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
std::cin >> ID;
}
std::string NAME; // create an variable nameed id to store the staff
// number entered from users
std::cout << "Please enter the name: " << std::endl;
// std::cin >> NAME;
while (std::getline(std::cin, NAME)) {
if (NAME.length() == 0)
{
std::cout << "Your input is not correct. Please re-enter your name" <<
std::endl;
}
// This will check if the NAME contains only characters.
else if (std::all_of(NAME.begin(), NAME.end(), isalpha)) // isalpha: The function returns a non-zero value if the argument is an alphabetic character, or zero otherwise.
{
break;
}
else {
std::cout << "Only characters are allowed:" << std::endl;
}
}
That is my test case.
*********************************************************
********Welcome to the employee management system********
***********0.Exit the management page********************
***********1.Add the employee information****************
***********2.Display the employee information************
***********3.Delete the employee information*************
***********4.Modify the employee information************
***********5.Search the employee information************
***********6.Sort by number*****************************
Please enter the numbers 0 through 6 as your next step
1
Please enter the number of staffs you want to add:
1
Please enter pure and positive number as the staff number of 1 staff:
12
Please enter the name:
Your input is not correct. Please re-enter your name
After I entered the employee number, the judgment condition was triggered before I entered the name, but I didn't enter a space, I didn't even have time to enter something, and the judgment condition was triggered.
When you get input form the user using std::cin the input from the user does not go directly into the program. Instead that input sits in a buffer, which temperately stores that user entered data so you can later tie that data to a variable or perform some other task with that data. However, if that buffer does not get cleared and you use std::getline then std::getline will read the buffer instead of the new user input that you actually wanted. This is why its important to make use of the std::cin.ignore() function, which will clear the buffer of unwanted int and characters. If you want a more en-depth overview of std::cin.ignore() check out this link .
The Fix:
Looking at your code you do make use of cin.ignore() to clear the buffer but only the user enters something other then a number which will drop them into that while loop.
This is what you currently have:
while (ID <= 0) {
std::cout << "Invalid staff number, please enter again: " << std::endl;
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
std::cin >> ID;
}
std::string NAME; // create an variable named id to store the staff
// number entered from users
std::cout << "Please enter the name: " << std::endl;
To correct this you will need that std::cin.ignore() call out side of the while loop so that it always happens whether there is an error or not. I have a comment that says NEW CODE LINE for where I made the change.
while (ID <= 0) {
std::cout << "Invalid staff number, please enter again: " << std::endl;
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
std::cin >> ID;
}
std::cin.ignore(INT_MAX, '\n');//NEW CODE LINE
std::string NAME; // create an variable named id to store the staff
//number entered from users
std::cout << "Please enter the name: " << std::endl;
I want my function to work so that if someone enters more grades than the 20 allowed it returns to another point, whether in the function or out of it, so that the user has the option to try again. What do I need to change, I know return can't be the answer as it just exists the function and goes to the next line after the function call. This is for homework, and I'm honestly not sure this is even necessary, I just want it to be clean and handle user errors.
void gradeTaker()
{
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
if (gradeCounted > arraySize)
{
cout << "You entered a number of grades greater than 20, try again \n";
return;
}
}
The current result of my code is it exits the function and continues to the following line. I don't know the code necessary for what I want.
you can use while loop to take the input with the condition:
void gradeTaker() {
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
while (gradeCounted > arraySize) {
cout << "You entered a number of grades greater than 20, try again \n";
cin >> gradeCounted;
}
// do whatever with gradeCount
}
Also do a while loop, label with goto statement, and some other logic to achieve.
Call the function 'gradeTaker()' from inside itself instead of 'return'
I'm trying to create a function that uses dynamic allocated arrays instead of vectors because I want to see how they work. Basically, this function asks the user to input how many people they are going to enter followed by their name; then, they enter how many of these people want to register for an ID followed by their phone #.
For example:
"How many customers will you like to enter? " 3 //user inputs 3
Bob Allen //user input
Ellen Michaels //user input
Jane Andrews //user input
"How many people want to register for the VIP ID? " 4 //user inputs 4; user can enter a new name here if they forgot to enter it the first time
Jane Andrews 213-2312
Bob Allen 111-1212
Jonathan Drew 211-9283
Michael Jacks 912-3911
//what the program spits out after the function is implemented
Final Registration: Guaranteed VIP IDs
Bob Allen 111-1212
Ellen Michaels NOT GUARANTEED
Jane Andrews 213-2312
//The new users entered in the 2nd round will not be listed in the final registration because it is too late for them to sign up
Basically, the problem I'm having is:
1. How to check if the person is not listed in the second round
2. Ignore the new people the user entered in the second round
3. Print the final registration in the same order the user entered the names in the first round
This is what I have right now, but this only works if the same number of users is entered the first and second time around. It does not check if there are new or omitted
string* people;
cout << "How many customers will you like to enter? " << endl;
int howmany;
cin >> howmany;
people = new int[howmany];
for (int i=0;i<howmany;i++)
{
cin >> people[i];
}
cout << "How many people want to register for the VIP ID? " << endl;
int num_of_register;
string* vip;
cin >> num_of_register;
vip = new int[num_of_register];
for (int i=0;i<num_of_register)
{
cin >> vip[i];
for (int j=0;j<howmany;j++)
{
if (num_of_register == howmany) {
if people[j] == vip[i] //check if they're the same people or not
cout << "Final Registration: Guaranteed VIP Ids" << endl;
cout << people[i];
else {
//check if the names are the same
}
}
}
Any guide/advice will be helpful. I'm not sure how to approach this problem. Thank you!
First you get howmany and allocate memory for people. In the second round, there is a chance that user enters a new person. You can first get number of customers and then their names and in the second part, check if the name exist in the first part
cin >> num_of_register;
if( num_of_register > howmany )
{
cout << "You can't register new people\n";
}
for (int i=0;i<num_of_register; i++)
{
cin >> vip[i];
int customerExists = -1;
for (int j=0;j<howmany;j++)
{
if( people[j] == vip[i] )
{
customerExists = i;
break;
}
}
if(customerExists == -1)
{
cout << "You can not enter new customer\n";
// get people[i] again
i--;
}
else
{
cout << "Final Registration: Guaranteed VIP Ids" << endl;
cout << people[customerExists];
}
}
I'm new to C++. I decided to not watch the next tutorial and put my skills to use, by making a funny Mind Reader application. I'm pleased with myself, however, even though I've ironed out most bugs, I still have one concerning the exit function. I read the C++ documentation for it, and I'm not sure what I did wrong. I did exit(0);. I have a very weird error, which is:
no match for call to '(std::string {aka std::basic_string<char>}) (int)
I have searched online, however I am still unaware of what the problem is. My error is on line 59 (marked in the code):
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
//declaring variables to be used later
string name;
string country;
int age;
//header goes below
cout << "#######################################";
" ############ MIND READER ############"
"#######################################\n\n";
//asks if the user would like to continue and in not, terminates
cout << "Would like you to have your mind read? Enter y for yes and n for no." << endl;
cout << "If you do not choose to proceed, this program will terminate." << endl;
string exitOrNot;
//receives user's input
cin >> exitOrNot;
//deals with input if it is 'y'
if (exitOrNot == "y"){
cout << "Okay, first you will need to sync your mind with this program. You will have to answer the following questions to synchronise.\n\n";
//asks questions
cout << "Firstly, please enter your full name, with correct capitalisation:\n\n";
cin >> name;
cout << "Now please enter the country you are in at the moment:\n\n";
cin >> country;
cout << "This will be the final question; please provide your age:\n\n";
cin >> age;
//asks the user to start the sync
cout << "There is enough information to start synchronisation. Enter p to start the sync...\n\n";
string proceed;
cin >> proceed;
//checks to see if to proceed and does so
if (proceed == "p"){
//provides results of mind read
cout << "Sync complete." << endl;
cout << "Your mind has been synced and read.\n\n";
cout << "However, due to too much interference, only limited data was aquired from your mind." << endl;
cout << "Here is what was read from your mind:\n\n";
//puts variables in sentence
cout << "Your name is " << name << " and you are " << age << " years old. You are based in " << country << "." << endl << "\n\n";
cout << "Thanks for using Mind Reader, have a nice day. Enter e to exit." << endl;
//terminates the program the program
string exit;
cin >> exit;
if (exit == "e"){
exit(0); // <------------- LINE 59
}
}
}
//terminates the program if the input is 'n'
if (exitOrNot == "n"){
exit(0);
}
return 0;
}
Thanks
The local variable exit shadows other identifiers from outer scopes with the same name.
To illustrate with a smaller example:
int main()
{
int i;
{
int i;
i = 0; // assign to the "nearest" i
// the other i cannot be reached from this scope
}
}
Since the only exit visible is an object of type std::string, the compiler sees exit(0) as a call to operator()(int) and throws a hissy fit when it doesn't find one among std::string members.
You can either qualify the name (std::exit(0);) or rename the variable. And since all of your code is in main you can simply say return 0; instead.
Try using return 0; or return EXIT_SUCCESS;. It's the exact same thing. Also, you can only input one word into a cin. Instead, use getline(cin, string name); If it still doesn't work, add a cin.ignore(); before your getline(cin, string name);, like this:
//stuff
string country;
cout << "Now please enter the country you are in at the moment:\n\n";
cin.ignore();
getline(cin, country);
//stuff
return 0;
The problem is arrising because you declared a standard keyword as the name of a local variable.
Now as the local variable is of type sting it is not able to take it as its value.
I am in the second phase of a project where I need to extend my program into a menu driven application to query the database I have on a .txt file. So, my trouble is that I cannot get my loop to be perpetual. It always terminates when it initializes from one option to the next. Here is the snippet of my code that is my int main:
int main ()
{
char Q,q;
char S,s;
char task;
string pathname;
string z;
int count=0;
cout << "Welcome to Jason Rodriguez's Library Database." << endl;
cout << "Please enter the name of the backup file: ";
cin >> pathname;
ifstream inFile(pathname.c_str());
while(!inFile.eof())
{
getline(inFile,z);
count++;
}
while (task != 'Q' || task != 'q') {
cout << count << " records loaded successfully." << endl;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
if ((task == 'Q')||(task =='q'))
{
cout << "Program will now terminate";
break;
}
else if ((task == 'S')||(task =='s'))
{
showAll (loadData (pathname));
cout << endl;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
}
}
}
I need to add two more options into the loop on top of these two but I figured I should get the first two working correctly first. The other two should be plug & chug after that. Basically what I was trying to do is say if the user enters Q or q, terminate the program. Else, if user hits S or s, activate showall function and after ward, go back to the original query. It isn't working though. Assistance is welcome and appreciated.
Menus almost always require loops - especially ones that require the user to enter the correct choice input. The most applicable one in a case like this is the while loop - but essentially, any other loop variant can be used.
UPDATE:
int main ()
{
char task;//this is the only char needed. Your other chars were redundant
string pathname;
string temp;//I changed z to temp to better reflect its purpose
int count=0;
cout << "Welcome to Jason Rodriguez's Library Database." << endl;
cout << "Please enter the name of the backup file: ";
cin >> pathname;
ifstream inFile(pathname.c_str());//this is potentially a problem in that you aren't verifying that the pathname is a valid one
//you did not check to see that your file was open, otherwise there is no way to tell that you successfully opened the file
if (inFile.is_open()) {
//while(!inFile.eof()) is a character by character read and comparison
//made your life easier by shortening it down to this - which ensures
//that a line is read. (Much faster and more readable)
while(getline(inFile,temp))
{
count++;
}
inFile.close();//always close a file after you've used it
//At this point the entire file has been read. So, this is where this message SHOULD be
cout << count << " records loaded successfully." << endl;
}
else {
//if there was an error opening the file (i.e. wrong path, or it simply does not exist), this will be displayed
cout << "There was a problem opening your file" << endl;
exit(0);//and the program will terminate
}
while (task != 'Q' || task != 'q') {
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
if ((task == 'Q')||(task =='q'))
{
cout << "Program will now terminate";
break;
}
else if ((task == 'S')||(task =='s'))
{
string author;
//showAll (loadData (pathname));
cout << endl;
cout << "Search an Author" << endl;
cin >> author;//get the author name to search from the user
//write code to search an author here
}
}
}
There are a number of issues with the code that you posted which I will forgo for the sake of brevity. Hence, note the following:
Your code was printing the same message per option (except for quit). Of course it would appear that it didn't work. Each option is a different task. Print what each task does (similar to what I did).
You wish to search the file for an author, but you have not stored it. Look into a way of storing it that appeases your instructor.
It would be ideal for you to use switch in this case, considering the increasing complexity of your code.
Try breaking down each task into functions, and call them to make your main function readable. In fact, it is a good programming practice for your main function to be as small as possible.
And, as juanchopanza quite rightly pointed out: you have some fundamental issues with C++. Try doing some more exercises and do more examples from a good C++ book.