the question asks me to repeat this program until users enter X. what should I do to loop this program? should I use while?
question: repeat the program until the user enter X for package code
#include <iostream>
using namespace std;
int main(){
int price_package;
char package_code;
int num;
int no_of_adults;
int no_of_childs;
cout<<"Enter package code: ";
cin>>package_code;
if(package_code=='A'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package= ((40*no_of_adults)+(21*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else if(package_code=='B'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package=((23*no_of_adults)+(14*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else if(package_code=='C'){
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
price_package=((38*no_of_adults)+(18*no_of_childs));
cout<<"price package: RM"<<price_package<<endl;
}
else{
cout<<"ERROR";
}
}
You could use a while loop or a do while loop. Both of which would look like the following:
// import and variables here
do{
// logic to loop
} while(package_code!='X')
Or
// imports and variables
//declare package_code with some value other than 'X'
while(package_code!='X'){
//loop logic
}
Try this
#include <iostream>
using namespace std;
void Output(int no_of_adults, int no_of_childs, int price_package)
{
cout<<"Enter number of adults: ";
cin>>no_of_adults;
cout<<"Enter number of childs: ";
cin>>no_of_childs;
cout<<"price package: RM"<<price_package<<endl;
}
int main()
{
int price_package;
char package_code;
int num;
int no_of_adults;
int no_of_childs;
while (1)
{
cout<<"Enter package code: ";
cin>>package_code;
if(package_code=='A')
{
price_package= ((40*no_of_adults)+(21*no_of_childs));
Output(no_of_adults, no_of_childs, price_package);
}
else if(package_code=='B')
{
price_package=((23*no_of_adults)+(14*no_of_childs));
Output(no_of_adults, no_of_childs, price_package);
}
else if(package_code=='X')
{
break;
}
else
{
cout<<"ERROR"<<endl;
}
}
}
Related
I'm trying to create a program that in the main() function enters to a menu using a switch. In each case invoques another functions. In the function createFile(), which it is supposed to create a binary file, fill it out with 0's and then add the info that is required in the first space is returning (1) and it says that the file couldn't be created. What am I doing wrong? What was my mistake?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct athletesInfo
{
int heartRate;
int time;
};
void createFile(fstream&);
void addInfo(fstream&);
void showInfo(fstream&);
int n;
int main(){
int op;
fstream fileA;
do
{
cout<<"MENU"<<endl;
cout<<"(1) Enter the first Heart Rate of an Athlete"<<endl;
cout<<"(2) Add Another Athlete"<<endl;
cout<<"(3) Show Info Athletes"<<endl;
cout<<"(4) Exit"<<endl;
cout<<"Choose an option: ";
cin>>op;
switch (op)
{
case 1:
createFile(fileA);
break;
case 2:
addInfo(fileA);
break;
case 3:
showInfo(fileA);
break;
default:
cout<<"Choose a correct option."<<endl;
break;
}
} while (op!=4);
return 0;
}
void createFile(fstream &fileA){
athletesInfo athle;
fileA.open("athletes.dat", ios::in|ios::out|ios::binary);
if (fileA.fail())
{
cout<<"The file couldn't be created"<<endl;
exit(1);
}
cout<<"How many registers would you like?"<<endl;
cin>>n;
for (int i = 0; i < n; i++)
{
fileA.seekg(i* sizeof(athletesInfo));
athle.heartRate=0;
athle.time= 0000;
fileA.write((char *)&athle, sizeof(athletesInfo));
}
cout<<"Enter the info of the first athlete"<<endl;
cout<<"Heart rate: ";
cin>>athle.heartRate;
cout<<"Time (00:00): ";
cin>>athle.time;
while (athle.heartRate<0 && athle.time>2359 && athle.time<0000)
{
cout<<"Wrong Inputs."<<endl;
cout<<"Enter the info of the first athlete"<<endl;
cout<<"Heart rate: ";
cin>>athle.heartRate;
cout<<"Time (00:00): ";
cin>>athle.time;
}
fileA.write((char *)&athle, sizeof(athletesInfo));
fileA.close();
}
void addInfo(fstream& fileAthletes){
};
void showInfo(fstream& fileAthletes){
};
So I took a C++ class in High School, but haven't done it in years, so I'm basically new. So I am wondering if there is a limit to the amount of cins you can do. It allows me to input 7 and then skips all the other inputs to go to the end. My guess is that there's a data limit. Is this correct?
#include <iostream>
using namespace std;
int main() {
int time1;
int time2;
int time3;
int time4;
int time5;
int time6;
int time7;
int time8;
int time9;
int time10;
cout<<"enter number";
cin>>time1;
cout<<"enter number";
cin>>time2;
cout<<"enter number 1";
cin>>time3;
cout<<"enter number 1";
cin>>time4;
cout<<"enter number 1";
cin>>time5;
cout<<"enter number 1";
cin>>time6;
cout<<"enter number 1";
cin>>time7;
cout<<"enter number 1";
cin>>time8;
cout<<"enter number 1";
cin>>time9;
cout<<"enter number 1";
cin>>time10;
cout<<"the end?";
}
You can use cins unlimited and you need to use loops. Here I provided example of fillind array buy cin.
#include <iosteam>
using namespace std;
int main(){
cout<<"Enter number of cins\n";
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cout<<"Enter "<<i<<" number\n";
cin>>a[i];
}
}
Your code should work fine if you only enter numbers. There is no limit to the amount of cins you can do. My guess is that you enter something that isn't a number, e.g. a string. When that happens cin's error flag is set and future attempts to get input will fail.
What you can do is add some input validation if you want. A simple if statement will do:
int num{0};
if (cin >> num)
{
....
}
If the input is not valid, i.e. the if condition is false, you need to clear the error:
cin.clear();
and discard everything remaining in the input buffer and newline:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You could use a std::vector to store the numbers instead of separate integer variables and use a do...while loop. Putting this all together your code could look like this:
#include <iostream>
#include <vector>
#include <limits>
int main()
{
std::vector<int> nums;
int n{0};
std::cout << "Enter total number to input" << std::endl;
std::cin >> n;
int i{0};
do
{
std::cout << "Enter number " << i+1 << std::endl;
int num{0};
if (std::cin >> num)
{
nums.push_back(num);
++i;
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input" << std::endl;
}
} while (i < n);
}
Note that I'm not using namespace std in my code. That's considered bad practice.
I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?
I get declaration syntax error in my code but i do not find any mis-typings or anything.Please help.I am using turbo c++ for my school level programming.
I get it where i have typed -void issue() (inside the main function)
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
class book {
char bookname[20];
char isbn[20];
char author[20];
char category[20];
float price;
int noc;
public:
void accept(){
cout<<"Enter book name :- \n";
gets(bookname);
cout<<"Enter isbn no of the book:- \n";
gets(isbn);
cout<<"Enter authour name:- \n";
gets(author);
cout<<"Enter category of book:- \n";
gets(category);
cout<<"Enter price of the book :- \n";
cin>>price;
cout<<"Enter no of copies of book available in the library :- \n";
cin>>noc;
}
void display() {
cout<<"Name of the book is :- ";puts(bookname);cout<<endl;
cout<<"ISBN :- ";puts(isbn);cout<<endl;
cout<<"Author :- ";puts(author);cout<<endl;
cout<<"Category :- ";puts(category);cout<<endl;
cout<<"Price :- ";cout<<price<<endl;
cout<<"No of copies available :- ";cout<<noc<<endl;
}
void issue();
}b[5];
int main() {
for(int i=0;i<5;++i) {
b[i].accept();
}
void issue() {
int flag=1;
char booksearch[20];
cout<<"Enter name of book member wants to issue :- \n";
gets(booksearch);
for(int i=0;i<5;++i) {
flag=strcmp(booksearch,b[i].bookname);
if(flag==0)
break;
}
if(flag==0) {
cout<<"Book found \n";
b[i].display();
b[i].issue();
} else {
cout<<"Book not available:- \n";
}
}
getch();
return 0;
}
main does not have a closing brace Put one in before void issue()
Now change void issue() to void book::issue()
Fix this then tell us any further errors along with the line that it occurs on
EDIT
Instead of 1) move
getch();
return 0;
}
To that location
Why is the following code not giving results and how to get results?
Whenever I run the code, it first asks for the names of the players of two teams playing the match, then it shows the menu from which if we select any one of the option it again asks for the batsman name which is not according to the program designed. My research on the code and the problem is that I think buffer memory is full but I don't know how to free it, any help would be beneficial. Thank you
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class scorecard{
char batname[11][20];
int runscored[11];
char situation[11][10];
char mode[11][15];
char bowlername[11][20];
float oversplayed[11];
int maiden[11];
int runsgiven[11];
int wicketstaken[11];
public:
void updatebatsman(void);
void updatebowler(void);
void displaybat(void);
void displaybowl(void);
void menu(void);
scorecard()
{for(int n=0;n<12;n++)
{
runscored[n]={0};
oversplayed[n]={0};
maiden[n]={0};
runsgiven[n]={0};
wicketstaken[n]={0};
}
}
};
int main()
{
int jb=0;
scorecard s1;
int kb;
s1.menu();
do
{
cout<< "Enter the option"<<endl;
cout<<"(1) Display batting score"<<endl<<"(2) Display Bowling score"<<endl<<"(3) Update batting score"<<endl;
cout<<"(4) Update Bowling score"<<endl;
cin >>kb;
switch(kb)
{
case 1 : s1.displaybat();
break;
case 2 :s1.displaybowl();break;
case 3:s1.updatebatsman();break;
case 4:s1.updatebowler();break;
default:cout<<"Wrong choice";
}
}while (jb<1);
}
void scorecard::updatebowler(void)
{char bowlname[20];
int str,k,option,overnumbers,maidenumb,uprun,upwicket;
cout<<"Enter Bowler name:";
cin.getline(bowlname,20);
for( k=0;k<11;k++)
{str= strcmp(bowlername[k],bowlname);
if (str== 0)
{
cout<<"Menu for Bowler information update "<<endl;
cout<<"(1) Update Number of overs"<<endl<<"(2) Update maiden overs"<<endl<<"(3) Update runs given"<<endl;
cout<<"(4) Update wickets taken"<<endl;
cin >> option;
switch(option)
{
case 1:{cout<<"Enter Numbers of overs to be updated:";
cin >>overnumbers;
cout<<endl;
oversplayed[k]+=overnumbers;
break;
}
case 2:{cout <<"Enter the number of maiden overs to be updated:";
cin>>maidenumb;
cout<<endl;
maiden[k]+=maidenumb;
break;
}
case 3:{cout <<"Enter the number of runs to be added:";
cin>>uprun;
cout<<endl;
runsgiven[k]+=uprun;
break;
}
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
}
default:cout<<"wroung choice";
}
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::updatebatsman(void)
{char batsmaname[20];
int str,k;
cout<<"Enter Batsman name:";
cin.getline(batsmaname,20);
for( k=0;k<11;k++)
{str= strcmp(batname[k],batsmaname);
if (str== 0)
{
cout<<"enter runs scored:";
cin>>runscored[k];
cout<<endl<<"enter weather out or not out:";
cin>>situation[k];
cout<<endl<<"enter mode(if batsman out) by which batsman was out:";
cin>>mode[k];
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::displaybat(void)
{
cout << "Batsman name"<<'t'<<"Runs scored"<<'t'<<"situation"<<'t'<<"mode"<<endl;
for(int j=0;j++;j<12)
{
cout<<batname[j]<<'t'<<runscored[j]<<'t'<<situation[j]<<'t'<<mode[j]<<endl;
}
}
void scorecard::displaybowl(void)
{
cout << "Bowler name"<<'t'<<"overs played"<<'t'<<"maiden overs"<<'t'<<"wicket taken"<<'t'<<"Runs given"<<endl;
cout<<endl;
for(int j=0;j++;j<12)
{
cout<<bowlername[j]<<'t'<<oversplayed[j]<<'t'<<maiden[j]<<'t'<<wicketstaken[j]<<'t'<<runsgiven[j]<<endl;
}
}
void scorecard::menu(void)
{
cout<<"Enter the name of players of batting team"<<endl;
for (int k=0;k<11;k++)
{
cout <<"Enter name of player "<<k+1<<":";
cin>>batname[k];
}
cout <<"Enter the name of players of bowling team"<<endl;
for (int n=0;n<11;n++)
{
cout <<"Enter name of player "<<n+1<<":";
cin>>bowlername[n];
}
}
This is very wrong:
for(int j=0;j++;j<12)
It should be:
for(int j=0; j < 11; j++)
You are also missing a break in your case 4 statement for the options:
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
break;
}
default:cout<<"wroung choice";
Without the break you will see also the output wrong choice when the user selects option 4.