I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}
Related
I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.
Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed
You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.
It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}
A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}
Using C++ (g++-4.7 on Mint 16).
Code is a unrefined (and unfinished) Tic-Tac-Toe game.
#include <iostream>
using namespace std;
int main()
{
//initial data
char turn='A';
char ttt[] = {'1','2','3','4','5','6','7','8','9'};
int move;
int over=0; //0 is no, 1 is yes
int valid=0;
while ( over == 0)
{
//display
cout << "\n" << ttt[0] << "|" << ttt[1] << "|" << ttt[2] <<"\n-----\n";
cout << ttt[3] << "|" << ttt[4] << "|" << ttt[5] <<"\n-----\n";
cout << ttt[6] << "|" << ttt[7] << "|" << ttt[8] <<"\n\n Choose a number (Player " << turn << "):";
//ask enter for play with turn
cin >> move;
cout << "\n";
valid = 0;
while (valid == 0)
{
//check if input is valid
if (((move > 0) and (move < 10)) and
((ttt[move-1] != 'A') and (ttt[move-1] != 'B')) and
(cin))
{
ttt[move-1] = turn;
valid=1;
}
else
{
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
}
//check if done if no //change turn then goto //display
if (((ttt[0]==ttt[1]) and (ttt[1]==ttt[2])) or
((ttt[3]==ttt[4]) and (ttt[4]==ttt[5])) or
((ttt[6]==ttt[7]) and (ttt[7]==ttt[8])) or
((ttt[0]==ttt[3]) and (ttt[3]==ttt[6])) or
((ttt[1]==ttt[4]) and (ttt[4]==ttt[7])) or
((ttt[2]==ttt[5]) and (ttt[5]==ttt[8])) or
((ttt[0]==ttt[4]) and (ttt[4]==ttt[8]))or
((ttt[2]==ttt[4]) and (ttt[4]==ttt[6])))
{
//display winner or say draw
cout << "Player " << turn << " wins!\n";
over=1;
}
else
{
//change turn
if (turn=='A')
{ turn='B';
}
else
{ turn='A';
}
}
}
return 0;
}
There seem to be a bug on the code. On the part where check if input is valid the and (cin) seem to be failing.
When entering a character, (Instead of a number) it output continuously stacks of:
Invalid slot. Choose a number (Player A or B):
I tested the rest of condition without it, it was all working well. Is there a problem on the code or is this really "cin" problem? I've also tried out !(!cin) but it's the same scenario.
You must clear the fail bit from the cin stream in your else block.
When you enter a character that isn't an integer, the cin stream sets the fail bit, which you correctly check for in your if statement, but you never clear it afterward. This causes your input validity check to be false forever.
#include <limits>
...
else
{
cin.clear(); // Add this line
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // And this one
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
For additional information, see the documentation for std::basic_ios::clear
Update: see this question and this question for similar problems.
Essentially, you also need to tell cin to ignore whatever is in the stream or it will continually set the fail bit with its bad contents you haven't cleared yet. I modified the above snippet to work.
as recommended I've been working through the book 'Jumping into c++'. I'm currently on problem 7 of chapter 5 and although I have produced the code that appears to do what is asked of me I was hoping someone might be able to take a look and tell me if I've implemented any 'bad' practice (Ideally I don't want to be picking up bad habits already).
Secondly, it also says 'try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered'. Again, the code below produces a horizontal bar graph but I'm not convinced that if I had say 10000 entries (I guess I could verify this by adding an additional for loop) that it would scale according. How would one go about applying this? (such that it always properly scales regardless of how many entries).
I should probably point out at this point that I have not covered topics such as arrays, pointers and classes as of yet in case anyone was curious as to why I didn't just create a class called 'vote' or something.
One final thing... I don't have a 'return 0' in my code, is this a problem? I find it slightly confusing as to what exactly the point of having return 0 is. I know that it's to do with making sure your code is running properly but it seems sort of redundant?
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int option;
int option_1 = 0;
int option_2 = 0;
int option_3 = 0;
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
while(option != 0)
{
if(option == 1)
{
option_1++;
}
else if(option ==2)
{
option_2++;
}
else if(option ==3)
{
option_3++;
}
else if(option > 3 || option < 0)
{
cout << "Not a valid entry, please enter again" << endl;
}
else if(option ==0)
{
break;
}
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
}
cout << "Option 1 (" << option_1 << "): ";
for(int i = 0; i < option_1; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 2 (" << option_2 << "): ";
for(int i = 0; i < option_2; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 3 (" << option_3 << "): ";
for(int i = 0; i < option_3; i++)
{
cout << "*";
}
}
About the return 0 in main : it's optional in C++.
About your code:
You have a ton of if / else if blocks, you should replace them with a switch. A switch statement is more compact, readable, and may be a little bit faster at runtime. It's not important at this point, but it's pretty good practice to know where to put a switch and where to use regular if.
You have one big function, it's really bad. You should break your code into small, reusable pieces. That's something called DRY (Don't repeat Yourself): if you are copy-pasting code, you're doing something wrong. For example, your sport list appears 2 times in your code, you should move it in a separate function.
You wrote cout << "" << endl;, I think you don't really understand how std::cout work. std::cout is an object representing the standard output of your program. You can use operator<< to pass values to this standard output. std::endl is one of these values you can pass, strings are, too. So you can just write cout << endl;, no need for an empty string.
Please learn how to use arrays, either raw ones or std::array. This is a pretty good example of a program which can be refactored using arrays.
Here is a more readable, cleaner version of your code:
#include <iostream>
int prompt_option()
{
int option;
while (true)
{
std::cout << "Which is your favourite sport?" << std::endl;
std::cout << "Tennis.. 1" << std::endl;
std::cout << "Football.. 2" << std::endl;
std::cout << "Cricket.. 3" << std::endl;
std::cin >> option;
if (option >= 0 && option <= 3)
return option;
else
std::cout << "Not a valid entry, please enter again" << std::endl;
}
}
void display_option(int number, int value)
{
std::cout << "Option " << number << " (" << value << "): ";
while (value--)
std::cout << '*';
std::cout << std::endl;
}
int main()
{
int option;
int values[3] = {0};
while (true)
{
option = prompt_option();
if (option)
values[option - 1]++;
else
break;
}
for (int i = 0; i < 3; i++)
display_option(i + 1, values[i]);
}
You have too much if else, it messy.
check out the code bellow, muc shorter, cleaner and efficent.
I hope it helps.
#include <iostream>
using namespace std;
int main()
{
int choice;
int soccer=0, NFL=0 ,formula1=0;
while(choice != 0){
cout<<"Please choose one of the following for the poll"<<endl;
cout<<"press 1 for soccer, press 2 for NFL, press 3 for formula 1"<<endl;
cout<<"Press 0 to exit"<<endl;
cin>>choice;
if(choice==1){
soccer++;
}
else if(choice==2){
NFL++;
}
else if(choice == 3){
formula1++;
}
else{
cout<<"Invalid entry, try again"<<endl;
}
cout<<"soccer chosen "<<soccer<<" times.";
for(int i=0; i<soccer; i++){
cout<<"*";
}
cout<<endl;
cout<<"NFL chosen "<<NFL<<" times.";
for(int j=0; j<NFL; j++){
cout<<"*";
}
cout<<endl;
cout<<"formula1 chosen "<<formula1<<" times.";
for(int c=0; c<formula1; c++){
cout<<"*";
}
cout<<endl;
}
return 0;
}
Please have a look at the following code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double balance=0;
int withdraw = 0;
double const bankCharges = 0.5;
cin >> withdraw >> balance;
if(withdraw%5==0 && balance>(withdraw+bankCharges))
{
cout << fixed << setprecision(2) << ((balance)-(withdraw+bankCharges)) << endl;
}
else if(withdraw%5!=0 || withdraw>balance)
{
cout << fixed <<setprecision(2) << balance << endl;
}
return 0;
}
The above code is created to address the below challenge
http://www.codechef.com/problems/HS08TEST
As you can see, my code is providing the correct answer. But the test engine says "wrong answer" !!!!! Why? Please help!
Never leave the if, else if block without an else condition if there is even a slight possibility to reach there. Add the else condition to your code.
if(withdraw%5==0 && balance>(withdraw+bankCharges))
{
cout << fixed << setprecision(2) << ((balance)-(withdraw+bankCharges)) << endl;
}
else if(withdraw%5!=0 || withdraw>balance)
{
cout << fixed <<setprecision(2) << balance << endl;
}
else
{
//Do something
}
I have to make my homework. It is console application which uses an array of structs that keep information about a computer(brand, year of manufactoring, weight and inventory number). So I wrote a completely working program, but I want to use a dynamic array, because I dont know how many records the user will input.
Is there way to do this. To add new records in array until the user say n/N? Any suggestions?
This is my version of program:
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ComputerInfo
{
char computerMark[20], invertarNumber[6];
unsigned int year;
float weight;
};
ComputerInfo computerArray[300];
ComputerInfo AddComputers(ComputerInfo compterArray[], int counter)
{
cout << "Enter mark of the computer: ";
cin >> computerArray[counter].computerMark;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
while ((computerArray[counter].year < 1973)
|| (computerArray[counter].year > 2013))
{
cout << "INVALID YEAR!!!" << endl;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
}
cout << "Enter computer weidth: ";
cin >> computerArray[counter].weight;
cout << "Enter computer invertar number(up to six digits): ";
cin >> computerArray[counter].invertarNumber;
return computerArray[counter];
}
void ShowRecords()
{
int counter = 0;
while (computerArray[counter].year != 0)
{
cout << "Mark: " << computerArray[counter].computerMark << endl;
cout << "Year: " << computerArray[counter].year << endl;
cout << "Weidth: " << computerArray[counter].weight << endl;
cout << "Inv. number: " << computerArray[counter].invertarNumber << endl << endl;
counter++;
}
}
void MoreThanTenYearsOld(ComputerInfo computerArray[])
{
int counter = 0;
float counterOldComputers = 0;
float computerPer = 0;
while (computerArray[counter].year == 0)
{
if (computerArray[counter].year <= 2003)
{
counterOldComputers++;
}
counter++;
}
computerPer = counterOldComputers / 3;
cout << endl;
cout << "Percantage of old computers is: " << computerPer << endl;
}
int main()
{
int counter = 0;
float computerPer = 0;
char answer = 'y';
for (int i = 0; i <= 299; i++)
{
strcpy(computerArray[i].computerMark,"");
}
while((answer == 'Y') || (answer == 'y'))
{
computerArray[counter] = AddComputers(computerArray, counter);
cout << endl;
cout << "Do you want to enter more records (Y/N): ";
cin >> answer;
cout << endl;
counter++;
}
MoreThanTenYearsOld(computerArray);
return 0;
}
Yes. Instead of your array, use
std::vector<ComputerInfo> computerArray;
and you can add as many objects as you want:
ComputerInfo c;
// read the data
computerArray.push_back(c);
now, computerArray[0] will have the info in c.
You'll need to #include <vector>.
Also, instead of char computerMark[20] you can use a std::string.
You have two options:
1) Use std::vector instead of an array. This is a very powerful tool and certainly worth learning how to use.
2) Dynamically allocate the array and resize it as you add more items. Basically this means writing your own version of std::vector. This is a good way to strengthen your programming skills. You will learn what goes into writing standard classes and functions. However, I advise using std::vector in more serious programming because it has already been thoroughly tested and debugged.