c++ User input validation in sorted array - c++

Hello i have a assinment that im making a weater program where we ask the user to enter info
first enter how many citys to use
then enter city name and degrees
then i will print out the list in order starting with the coldest city
and last i need to add a search funkar to search by degrees to find a location with that degrees
this one i havent started with
but my MAIN problem is that i need to validate that the user input is between -60 and 60 when enter the city and degrees... i just dont get it to work with anything... can someone please help out?`
cout<<"Enter Name of City and degrees \n\n";
for(i=0;i<n;i++){
cout<<"---------\n";
cin>>s_array[i].name;
cin>>s_array[i].degrees;
this is the code where user put in city and degree EX Rio 50
i just dont know how to validate it to be between -60 and 60`

What you're looking for, is simple data validation.
Assuming you have a struct City:
// used to hold the data
struct City {
string name;
double degrees;
};
and in your main(), you have initialised an array of these structs:
bool temperatureValid(const City);
int main() {
const int32_t totalCities = 12;
City cities[totalCities];
for (int32_t i = 0; i < totalCities; i++) {
// add data to structs
cout << "Enter city name: ";
cin >> cities[i].name; // you might want to validate this, too
cout << "Enter temperature: ";
cin >> cities[i].degrees;
cout << cities[i].name << " has a temperature of " << cities[i].degrees << "°" << endl;
if (temperatureValid(cities[i])) {
// cool... or not
} else {
cerr << "Invalid temperature range!" << endl;
--i; // make sure we can do this one again
continue;
}
}
return 0;
}
bool temperatureValid(const City city) {
return city.degrees >= -60 && city.degrees <= 60;
}

First of all, you should create a class. I understand from your code you must use class. If you don't have to it is easier than this. Then you should create an object.
Basic logic below here. You should create a class well.
class Weather //create class
Weather city // create object
cout<<"Please enter a city name:"<<endl;
cin>>city.name;
cout<<"Please enter a city degree:"<<endl;
cin>>city.degrees;

Related

How To Find Specific Data From A Text File and Change It?

I'm new to programming and I'm trying to change this code to write it to a text file.
Basically I have to find the price of an item that was stored in the array 'List', each pointer contains an item code, description, price and discount.
I'm having two problems though, finding the item's price in the text file and than changing it by the user's input.
void DoSetItemPrice(void)
{
int `searchCode` = 0;
double changePrice = 0.00;
cout << "Enter Code For Search: ";
cin >> searchCode;
cout << endl;
cout << "Enter Price Change: $";
cin >> changePrice;
cout << endl;
for (int i = 0; i < numItems; i++)
{
if (List[i].HasCode(searchCode) == true)
{
List[i].SetPrice(changePrice);
cout << "New Price: $" << List[i].GetDiscount();
} else
cout << "The Code You Entered Could Not Be Found";
}
}
i had this kind of situation before but my solution was kinda bad but here it is anyways,i don't know any pre defined functions in C++ that helps with string manipulation, but u can try entering a character before the price like 'ù' for example ,if the price is 100$ the string would become "ù100$" then based on that u can use a loop to check the text file u are reading and when ever u encounter the character 'ù' that means what comes after it is the price so u convert that part into numbers until u reach the '$' character which indicates the end of the price.

C++ How can i create Object automatically via program directly

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.

Looking for help on errors on my C++ code for functions and arrays

For my project in C++, I have been struggling with this project for a couple weeks now, and I feel like I have just confused myself with what I have added to this code. Can anyone give me some guidance as to what I'm doing wrong? Here are the errors I am getting right now:
151 29 [Error] could not convert '(FruitList*)(& itemsList)' from 'FruitList*' to 'std::string {aka std::basic_string}'
152 35 [Error] could not convert '(FruitList*)(& itemsList)' from 'FruitList*' to 'std::string {aka std::basic_string}'
Thanks!
I apologize if the code spacing is all messed up, this is my first post and I kept getting errors on how my code was spaced? Sorry in advance!
#include <iostream> //allows data to output to the screen
#include <string>
#include <vector>
using namespace std;
//function prototypes
void showFruitList (string);
void getData(string, int);
class Customer//create a class called customer
{
private://private section
//string all private variables
string firstName;
string lastName;
string streetAddress;
string city;
string state;
string zipCode;
public: //public sections
void setFName (string fName)//public function to set first name
{
firstName = fName;
}
string getFName ()//public function to get first name
{
return firstName;
}
void setLName (string lName)//public function to set last name
{
lastName = lName;
}
string getLName ()//public function to get last name
{
return lastName;
}
void setStreetAddress (string sAddress)//public function to set street ` address
{
streetAddress = sAddress;
}
string getStreetAddress()//public function to get street address
{
return streetAddress;
}
void setCity (string cty)//public function to set city
{
city = cty;
}
string getCity()//public function to get city
{
return city;
}
void setState (string sT)//public function to set state
{
state = sT;
}
string getState ()//public function to get state
{
return state;
}
void setZipCode (string zip)//public function to set zip code
{
zipCode = zip;
}
string getZipCode()//public function to get zip code
{
return zipCode;
}
};
struct FruitList //good for outputting lists of things to be called ` `in main function
{
string fruitItem; //string type
float fruitCostPP; //double type since prices for in decimal form ` `(fruit cost per pound)
};
//Establish customer registration and display a list of products
int main()
{
//declare variables
const int SIZE = 80;// assign value of 80 to SIZE
char firstName[ SIZE ];
Customer customer1 = Customer();//pulls from class Customer
string input;//welcome message and customer info input area
cout << "Welcome to Dried Fruit Central \n" <<endl;
cout << "Please enter your first name: "<< endl;//prompts user to enter ` `their first name
getline(cin, input);//user enters their first name
customer1.setFName(input);//pulls from class Customer
cout << "\nPlease enter your last name: " << endl; //promts user to ` ` `enter their last name
getline(cin, input);//user enters their last name
customer1.setLName(input);//pulls from class Customer
cout << "\nHello " << customer1.getFName() << "!"<< endl;// greeting to ` `user using their first name
cout << "\nPlease enter your street address: "<< endl;//prompts user for ` `their street address
getline(cin, input);//user enters their street address
customer1.setStreetAddress(input);//pulls from class Customer
cout << "\nPlease enter your city: "<< endl;//promts user to enter their ` `city
getline(cin, input);//user enters their city
customer1.setCity(input);//pulls from class Customer
cout << "\nPlease enter your state abbreviation: "<< endl;// prompts ` ` `user to enter their state abbreviation
getline(cin, input); //user enters their state abbreviation
customer1.setState(input);//pulls from class Customer
cout << "\nPlease enter your zip code: "<< endl;//promts user to enter ` `their zip code
getline(cin, input);//user enters their zipcode
customer1.setZipCode(input);//pulls from class Customer
cout << "\nThank you " << customer1.getFName() << ", you are now ` ` `registered and can begin shopping with \nDried Fruit Central! \n"<< ` ` endl;// lets customer know they are now registered and can begin ` ` shopping
cout << "\nHere is a list of our dried fruit available for purchase and ` `price per pound: \n"<< endl;//OUtput to customers the list of dried ` ` will be displayed as well as the price per pound
FruitList itemsList[8]; // 8 items on the menu
int itemNum = 0;//
char inputItemNum;//customers input fruit item number
vector<int> customerOrder;//customers order
while (true)//begin while loop
{
float totalCost=0;//double due to decimal amounts
getData(itemsList, 8); //pull from function getData
showFruitList(itemsList, 8); // pull function showFruitList
cout<<"Enter your orders. Press Enter after every input. Enter 0 to ` `end"<<endl;//customer inputs item numbers
do
{
while((cin>>itemNum).fail() || itemNum < 0 || itemNum > ` ` ` `9)//while loop to prevent customer from inputting the wrong item ` `number
{
cout<<"Enter correct item number : ";//error message
cin.clear();
cin.ignore();
}
customerOrder.push_back(itemNum - 1);
}while(itemNum != 0);
cout<<endl<<"You ordered"<<endl;//displays order total and items ` ` purchased
for(int i = 0; i < customerOrder.size() - 1; i++)
{
cout<<itemsList[customerOrder.at(i)].fruitItem<<"\t\t$ " ` ` ` `<<itemsList[customerOrder.at(i)].fruitCostPP<<endl;
totalCost += itemsList[customerOrder.at(i)].fruitCostPP;//all ` ` calculations
}
cout <<endl<<"Your order total is: $" << totalCost << endl << ` ` endl;//displays total cost
cout << "Input 'n' for a new order or 'Q' to quit \t";//allows users ` `to start new order or quit this order
cin >> inputItemNum;
if (inputItemNum == 'q' || inputItemNum == 'Q')
{
return 0;
}
else while (inputItemNum != 'n')//else while loop for error ` ` ` selection
{
cout << "Please make a valid selection.\t";//output error for ` ` valid selection to be entered
cin >> inputItemNum;
}
cout << endl << endl;
}
// system("pause");
return 0;
}
void showFruitList(FruitList list[], int size) //calls in structure ` `of fruit menu and price together to be displayed when called in main
{
cout << "Type the number of the items that you would like.""\n";
cout << "After each selection, press Enter." "\n";
cout << "To add multiple orders of the same fruit enter the same item ` `number." "\n\n\n" << endl;
cout << "When you are done, type 0 and press Enter to get your order ` `total." "\n\n\n" << endl;
for (int i = 0; i < size; i++) //goes with size of list 8, and adds a ` `.) and $ in front of each item
{
cout << "\t\t" << i + 1 << ") " << list[i].fruitItem << "$ " << ` ` list[i].fruitCostPP << endl; //structure. i+1 to start num at 1 ` ` rather than 0
cout << "\n";
}
return;
}
void getData(FruitList list[], int size) //two arrays that list the ` `item and one for the price 0-8
{
list[0].fruitItem = "Apricots.\t\t"; //items array starts at 0. ` ` output at 1.
list[0].fruitCostPP = 1.75;//price array starts at 0
list[1].fruitItem = "Apples.\t\t";
list[1].fruitCostPP = 1.25;
list[2].fruitItem = "Bananas.\t\t";
list[2].fruitCostPP = 1.25;
list[3].fruitItem = "Cherries.\t\t";
list[3].fruitCostPP = 2.25;
list[4].fruitItem = "Cranberries.\t\t";
list[4].fruitCostPP = 1.25;
list[5].fruitItem = "Mangos.\t\t";
list[5].fruitCostPP = 1.75;
list[6].fruitItem = "Peaches.\t\t";
list[6].fruitCostPP = 1.25;
list[7].fruitItem = "Strawberries.\t";
list[7].fruitCostPP = 1.75;
}
It has nothing to do with the function prototypes, but with the structure definition.
If you want to actually use a structure, it must be defined in full. It's okay to put function definitions (the implementation) after you call the functions, but for structures that's not possible.
To declare an actual variable of a structure the compiler needs the full definition of the structure, or the compiler won't know what members it contains or how big it is.
So to solve your problem don't have a simple forward declaration of the structure at the top, put the whole structure definition there.

Compare two arrays C++

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];
}
}

C++ file input/output and array assistance

I have a C++ project to do for my class and it's quite intricate, to me at least. I've got the general idea and concept down, but i'm running into some other problems when it comes to the arrays and file stuff. Below is what the project consists of
You will be building and modifying a class roster system for a Teacher to manage his class roster and their final grades. This program
will use functions for the various menu options, and you will work with
the data in arrays or vectors. The program will provide a menu system that allows for the teacher to perform tasks until he chooses to close the program. The program will read and write to a file called
classroster.txt. Any and all additions, deletions, or changes to the roster will be saved in classroster.txt file.
This file will contain the names of each of the students in the class with their grade. See the following for an example listed below of how the data would be stored in the classroster.txt file. You should work with the data using arrays or vectors.
Jim Jones C
Kevin James B
Marc Cohen A+
When the program starts it should read the data from the classroster.txt into arrays or vectors. While the program is running it should use the arrays or vectors for the functions while using the program. When the program ends it should overwrite the classroster.txt file if something has been changed. The
programs menu will offer the following options and will allow the user to keep performing functions until they choose to exit the program ( hint !!!!! you will need to use a loop for the menu system)
Add A New Student-
This will allow the user to add a new student to the system. The system should prompt for the new students full name and then grade.
It should validate that the grade is in the following values
(A+, A, A-, B+, B, B-,C+,C, C-, D+, D, D-, F) and if not
in the approved list it should prompt the user for a valid grade.
Change a Students Grade-
This will find the student in question and change the grade. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to
change their grade.
Remove a Student-
Will remove a student and their grade from the roster. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to remove.
Display Class Roster–
(Bonus Points if you can display the names is alphabetical order) This
function will display the list of all the students and their grades on
the screen that looks like this:
Student Name Grade
Jim Jones C
Kevin James B-
Marc Cohen A+
This is what i have so far, it's obviously not done yet
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
const int num_of_students;
const int new_student = 1, change_grade = 2, remove_student = 3, display_roster = 4, quit = 5;
int classroster[num_of_students];
int student_grade[num_of_students];
string possible_grades[13] = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"};
int choice;
ofstream class_file;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
cout << "---MENU---" << endl;
cout << "1. Add A New Student" << endl;
cout << "2. Change A Students Grade" << endl;
cout << "3. Remove A Student" << endl;
cout << "4. Display Class Roster" << endl;
cout << "5. Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == new_student) {
for (int index = 0; index < num_of_students; index++) {
class_file.open("classroster.txt");
cout << "What is the name of the student you want to add? ";
getline(cin, classroster);
if (student_grade == possible_grades) {
cout << "What is the final grade of this student? ";
getline(cin, student_grade);
}
else {
"Please enter a valid grade!"
}
cout << "Student added!";
}
}
else if (choice == change_grade) {
class_file.open("classroster.txt");
cout << "What is the name of the student whose grade you want to change? ";
getline(cin, )
}
else if (choice == remove_student) {
}
else if (choice == display_roster) {
}
else if (choice == quit) {
}
else {
cout << "Please enter a valid choice!"
}
system("PAUSE");
return 0;
}
First, to answer your question, here's one way to search an array of student names:
int index = -1;
for(int k=0; k<num_of_students; ++k)
{
if(names[k] == name)
index = k;
}
And here's a way to change the array of grades:
student_grade[index] = 3;
More generally, you taking the wrong approach. Your code does not compile, so it looks as if you're writing it all out before testing any of it. As they never seem to teach in school, you should start with something small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work.
Let's start with the number of students:
int main() {
const int num_of_students;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
return(0);
}
Try to compile this, and you'll find that there's something wrong. Fix it and try constructing an array of int and filling it in. Once that's working, try an array of string. Small steps.
You realy should be using maps for this question, its makes the most sense. Here is code to read in the map from a file. After you have the map all the operations you need are already implemented in the STL. I realize you may need to use vector but I'd like to think you wouldn't be penalized for being clever and actually writing a proper solution.
#include <map>
#include <fstream>
#include <iostream>
using namespace std;
int main(){
map<string,string> data;
fstream fs("classroster.txt");
while(fs.good()){
string fname, lname, grade;
fs >> fname;
fs >> lname
fs >> grade;
fname += lname; //Concat Names to get full
if(grade == "A") //Check other grades as well.
data.emplace(fname,grade);
}
while(1){
string option;
std::cout << "Options:" << endl;
cin >> option;
//Your option selection code here
}
return 0;
}
EDIT:
maps are also sorted by key name so printing alphabetically is very easy, no sorting required.
for(auto& pairs : data)
cout << pairs.first << " " << pairs.second << endl;