Console bar charts and division of results based on highest? | C++ - c++

So I've been reading a C++ Primer that has all kinds of examples and test scenarios inside that are good to make sure each new chapter has been correctly learnt and that there's no other way to improve that actually coding.
The C++ Primer asked for this "Practice Problem" to be attempted and is as follows:
Write a program that provides the option of tallying up the results of a poll with 3 possible values. The first input to the program is the poll question; the next three inputs are the possible answers. The first answer is indicated by 1, the second by 2, the third by 3. The answers are tallied until a 0 is entered. The program should then show the results of the poll—try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered.
So I was curious as to how the author wanted me to make sure that the results fit the screen resolution regardless of "how many results were entered" and after entering the main syntax for the loops that input the data and display. I was curious what the best way to go about this and slapped together a very, VERY simple work around that'll divide by a 1:10 ratio dependant on the highest result input (up to 1000/100)
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Variable decleration
string Question;
int tally1 = 0, tally2 = 0, tally3 = 0;
int input = 1;
int resultRatio;
//Question input and text fluff
cout << "Please enter a poll that has 3 answers: ";
getline(cin, Question, '?');
cout << "Your question is: " << Question << "?" << endl;
cout << "When results are complete for specified poll answer, enter 0 to input results" << endl;
while (1) //Tally 1 answer input.
{
cout << "Please enter the tallies for answer A: ";
cin >> input;
tally1 = tally1 + input;
if (input != 0)
{
cout << "A's current tallies: " << tally1 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 2 answer input.
{
cout << "Please enter the tallies for answer B: ";
cin >> input;
tally2 = tally2 + input;
if (input != 0)
{
cout << "B's current tallies: " << tally2 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 3 answer input.
{
cout << "Please enter tallies for answer C: ";
cin >> input;
tally3 = tally3 + input;
if (input != 0)
{
cout << "C's current tallies: " << tally3 << endl;
continue;
}
cout << endl;
break;
}
// Ratio in which total tallies should be divded by before bar chart display
if (tally1 >= 10 || tally2 >= 10 || tally3 >= 10)
{
resultRatio = 10;
}
else if (tally1 >= 100 || tally2 >= 100 || tally3 >= 100)
{
resultRatio = 100;
}
else if (tally1 >= 1000 || tally2 >= 1000 || tally3 >= 1000)
{
resultRatio = 1000;
}
else
{
resultRatio = 1;
}
//Simple bar chart to display all the results in a ratio that'll fit the screen thanks to resultRatio division
cout << "All results have been entered, here is the barchart (Results displayed are divided by " << resultRatio <<"):";
cout << endl << "A:" << "(" << tally1 << "votes )";
for (int i = tally1 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "B:" << "(" << tally2 << "votes )";
for (int i = tally2 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "C:" << "(" << tally3 << "votes )";
for (int i = tally3 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << "\nHere is the full bar graph on input results";
return 0;
}

Related

how to accept only whole numbers in c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to programming and I need help with my term project. I have made a program that simulates a hotel booking, the problem is that whenever a non-whole number is entered for the first question, it goes into an infinite loop. If you get to the second question and enter a non-whole number it accepts it as a whole number by dropping off anything that comes after the decimal and then skips the next question and stops running the program.
#include <iostream>
#include <string>
using namespace std;
int stay_length (int stay)
{
int nights = stay;
int total = 0*nights;
return total;
}
int rooms_booking(int rooms)
{
int rooms_booked = rooms;
int total = 0;
if(rooms_booked > 0)
{
total = rooms_booked * 50;
}
else
{
total = 0;
}
return total;
}
int main(){
int x;
string repeat;
int nights;
int total = 0;
int rooms_avail = 10;
int rooms;
cout << "Hello! Welcome to Hotel COMP 150." << endl;
do {
if (rooms_avail > 0) {
cout << "How many nights will you be staying?" << endl;
}
else {
cout << "Sorry, but there are no rooms available. " << endl;
}
do {
cin >> nights;
if (nights > 0 && nights <= 28)
{
int total1 = stay_length(nights);
cout << "You are staying for " << nights << " nights" << endl;
cout << "That costs: $" << total1 << endl;
total = total + total1;
}
else
{
cout << "You cannot stay less than 1 or more than 28 nights" << endl;
}
} while (nights <= 0 || nights >28);
if (rooms_avail > 0)
{
cout << "How many rooms will you be booking?" << endl;
cout << "There are " << rooms_avail << " available." << endl;
cin >> rooms;
if (rooms > 0 && rooms <= rooms_avail)
{
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else if (rooms <= 0 || rooms > rooms_avail)
{
do{
cout << "You can only book a minimum of 1 room or a maximum of " << rooms_avail << endl;
cin >> rooms;
} while (rooms <= 0 || rooms > rooms_avail );
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else
{
cout << "You cannot book more than " << rooms_avail << endl;
}
}
else
{
cout << "Sorry, all rooms have been booked." << endl;
}
cout << "Your total so far is: $" << total << endl;
cout << "Would you like to make another booking? Enter 'Y' or 'y' to do so." << endl;
cin >> repeat;
}while(repeat == "Y" || repeat == "y");
return 0;
}
It's always better to use std::getline() instead of operator>> to read interactive input from std::cin.
operator>> is not for reading a single line of text from standard input, and storing it. That's what std::getline() is for.
If the wrong kind of input is entered, not what operator>> expects, it sets std::cin to a failed state, which makes all future attempts to read std::cin immediately fail, resulting in the infinite loop you are observing.
To do this correctly, it is going to be either:
1) Always check fail() after every operator>>, to see if the input failed, if so recover from the error with clear(), then ignore(). This gets real old, very quickly.
2) It's much easier to read a single line of text with std::getline(), then parse the input yourself. Construct a std::istringstream, if you wish, and use operator>> with that, if that makes it easier for you.
You can achieve basic user-input error checking via the console with something along these lines:
int nights = 0;
// error checking loop
while(1) {
std::cout << "How many nights will you be staying?" << endl;
std::cin >> nights;
// input valid
if(!std::cin.fail() && (std::cin.peek() == EOF || std::cin.peek() == '\n')
&& nights > 0 && nights <= 28) {
// do stuff
break; // break from while loop
}
// input invalid
else {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "An input error occurred." << std::endl;
}
}

making numeric input value blink with different color for sudoku game

I am currently working on a sudoku game and I need help in adding a functionality that will make a value I input after selecting a row and column to flash red if wrong and green if correct
how do you make an input value flash green color when the right number is inputed by the user.
this is what my code look like for now.
if (randomize == 1)
{
for (int i = 0; i < 70; i++)
{
printGrid1();
cout << "Select row number: ";
cin >> row;
cout << endl;
cout << "Select column number: ";
cin >> col;
cout << endl;
cout << "Input Answer: ";
cin >> maybe;
cout << endl;
//Funtion to restart game
if ( col == 10|| row == 10 || answer ==10)
{
printTitle();
selectDifficulty();
}
//Check for out of bound cells
if (row > 9 ||col>9 ||row <1|| col<1)
{
cout << "This row or column is not in the Sudoku Board"<< endl;
}
answer = easyGuessNumGrid1Answer[row-1][col-1];
if (maybe != answer){
score = score - 5;
cout << "Your score is :" << score <<endl;
}
if (maybe == answer)
{
cout << "Good job! " << maybe << " was the right number. " << endl;
easyGuessNumGrid1[row-1][col-1] = answer;
i++;
}
else
{
cout << "incorrect, please try again..." << endl;
i--;
}
}}

Why does one of my 'while' statements execute when another one of my 'while' statements is true?

Note: I am using C++
Why does one of my 'while' statements ('while' number 1) execute anyway when another one of my 'while' statements ('while' number 2) placed above it is valid? This bothers me, because though 'while' number 1 is not true, but 'while' number 2 is true, 'while' number 1 executes anyway instead of 'while' number 2. Can anyone help me, or explain this? Here is my code:
#include <iostream>
#include <string>
using namespace std;
void PancakeGlutton()
{
int answer;
cout << "Good morning!" << endl;
cout << "Would you like to enter pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
while (answer == 1) {
int totalPeople = 10;
int totalPancakes = 0;
int input;
int lowest = 100000;
int highest = 0;
for (int i = 9; i >= 0; --i) {
cout << "How many pancakes did you eat this morning? I will be asking this question " << i << " more times." << endl;
cin >> input;
totalPancakes += input;
if (input >= highest) {
highest = input;
}
if (input <= lowest) {
lowest = input;
}
}
double pancakeAverage = double(totalPancakes) / double(totalPeople);
cout << "The total number of pancakes eaten was " << totalPancakes << " pancakes " << endl;
cout << "The average number of pancakes eaten was " << pancakeAverage << " pancakes " << endl;
cout << "The highest number of pancakes eaten was " << highest << " pancakes" << endl;
cout << "The lowest number of pancakes eaten was " << lowest << " pancakes" << endl;
cout << "" << endl;
cout << "Do you want to enter more pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
}
// while number 1:
while (answer == 2) {
break;
}
// while number 2:
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
}
int main()
{
PancakeGlutton();
system("PAUSE");
return EXIT_SUCCESS;
}
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
must be
while (answer != 1 && answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* Write a program that provides the option of tallying up the
* results of a poll with 3 possible values.
* The first input to the program is the poll question;
* the next three inputs are the possible answers.
* The first answer is indicated by 1, the second by 2, the third by 3.
* The answers are tallied until a 0 is entered.
* The program should then show the results of the poll—try making
* a bar graph that shows the results properly scaled to fit on
* your screen no matter how many results were entered.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}

How to code 'switch' statements concisely to guess a number the user is thinking of

I'm studying Bjarne Stroustrup's "Programming Principles and Practice Using C++". In Chapter 4 you are to create a game where the user thinks of an integer between 1 to 100 and the computer should ask questions to guess the answer. Ideally you should have the answer within 7 questions. My intuition is to ask half of each possible range repeated multiple times, e.g. at first when the range possibilities are 1 to 100 ask the question "Is the number you are thinking of greater or equal to 50?".
Here is a part of my solution showing how I was nesting the switch statements:
char user_answer;
cout << "Is the number >= 50? Answer "yes" or "no" by inputting 'y' or 'n': \a\n";
cin >> user_answer;
switch (user_answer)
{
case 'y':
cout << "Is the number >= 75? Answer "yes" or "no" by inputting 'y' or 'n': \a\n";
cin >> user_answer;
switch (user_answer)
{
case 'y':
cout << "Is the number >= 87? Answer yes or no (you get the idea): \a\n";
cin >> user_answer;
switch (user_answer)
{
While hypothetically creating every eventual yes and no case would result in accurate logic, this code is difficult to maintain and create. Should I be attempting this with a while loop? Functions? I attempted a 'for' loop but I could not implement repetition of the logic explained above.
You're supposed to think of a way where you write as few duplicate code lines as possible.
Yes, you should use a while loop, and appropriate calculations based on the user's answer to further narrow the number range you're asking on each pass of the loop.
You should be thinking about how to make one piece of code that works for every step of the questioning, not a web a if statements.
As an example, you can store an array of possible values [1,100] and have a recurring question that asks whether its larger than the centre of that array.
Depending on the answer you remove the values in the array that are no longer possible and ask again from the new centre of the array. From there you only need a condition check to see if you have an array of size 1 (meaning you know the answer).
i am just starting out on the Stroustrup coursebook as well.
The concepts introduced in chapter 4:
1. iterations
2. Functions
3. vectors
After looking at the advice posted here,
below is what i have. There were alot of trial and error to make sure that i have captured all the numbers.
cout << "Think of a number from 1 to 100, then press y and enter to continue.\n";
char c;
cin >> c;
int min = 1;
int max = 100;
int half(int, int);
vector<int> number;
for (int i = min; i <= max; i++){
number.push_back(i);
}
cout << "Is your number from " << number[min - 1] << " to " << number[(max / 2) - 1] << "? y/n. \n";
// the aim of this loop is to
// 1. bring up the min number to the halfway point between min and max everytime user answer no.
// 2. bring down the max number to the halfway point everytime user answer yes.
while((cin >> c)&&(min!=max)){
if (c == 'n'){
min = half( min, max);
}
else if (c == 'y'){
max = (max + min) / 2;
}
else
{
cout << "I dont understand your input!\n ";
}
cout << "min: " << min << "\t max: " << max << '\n'; // track the limits of the number
if (min == max){
cout << "Your number is " << min << "!\nPress ctrl-z!\n";
}
else if ((min+max)%2)
cout << " Is your number from " << number[min - 1] << " to " << number[half(min, max) - 2] << "? y/n.\n";
// because we added extra 1 in the half function for odd sums, we have to compensate here by deducting 2.
else
cout << " Is your number from " << number[min - 1] << " to " << number[half(min,max)-1] << "? y/n.\n";
}
keep_window_open(); // part of std_lib header, prompts enter character to exit
}
int half (int x, int y){
if ((x + y) % 2){
return ((x + y) / 2) + 1; // because division always round down, so for odd number division we add 1 to be inclusive.
}
else
return (x + y) / 2;
You should go for a function and tell the function what you want it to do.
Here is a quick example that leaves room for improvement.
But you should clearly see that there is a function that gets parameters as an input.
This allows you to use the function multiple times.
I think i know the game you want to program, so the next step is to find the math that generates the new values to call the query function again.
#include <iostream>
#include <string>
int QueryRange(int low, int high, int * result)
{
int error = 0;
using std::string;
using std::cout;
using std::endl;
using std::cin;
string str;
cout << "Is your Number n in the following range? " << low << " <= n <=" << high << " (y/n)" << endl;
cin >> str;
if(0 == str.compare("n"))
{
*result = 0;
}
else if(0 == str.compare("y"))
{
*result = 1;
}
else
{
*result = -1;
error = 1;
}
return error;
}
int main(int argc, char ** argv)
{
using std::cout;
using std::endl;
int low = 1;
int high = 100;
int ret;
while(0 != QueryRange(low, high, &ret))
{
cout << "Unable to read your input" << endl;
}
cout << "your answer was " << ((1 == ret) ? "y" : "n") << endl;
return 0;
}
This is for Chapter 4 Exercise 4 p.128 and is my solution after everyone's input. I wasn't able to use peoples suggestions directly due to the limitations of where I am at in the text book and how the question is worded. I was able to guess the users number in 7 questions or less. Thanks to everyone for the input.
// p128 Exercise 4 write a program to make a numbers guessing game. Use if, else,
// <, and =<, to find the answer of a number 1 to 100 in seven questions or less.
#include "C:\Users\X\Documents\Visual Studio 2013\Projects\std_lib_facilities.h.txt"
int main()
{
char user_answer = ' ';
int min_val = 1;
int max_val = 100;
int quest_number = 0;
int x = 0;
cout << "Welcome to the guessing game!\n-------------------------------------------------------------------------------\n\n";
cout << "Please think of a number from 1 to 100.\n";
cout << "This program will guess what number you chose by asking you yes or no questions. Answer truthfully.\n\n";
cout << "Here is my first of seven questions or less. ";
quest_number = max_val / 2;
for (int i = 1; i < 8; ++i)
{
if (min_val == max_val)
{
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
cout << "The number you are thinking of is " << min_val << "!\n";
keep_window_open("~");
return 0;
}
else if (max_val > 100 || min_val < 1 || min_val > 100 || quest_number > max_val || quest_number < min_val)
{
cout << "The program has had an error. Exiting.\n";
keep_window_open("~");
return 0;
}
else if (max_val - min_val == 1)
{
cout << "Is your number greater than " << min_val << "? Answer yes or no by typing 'y' or 'n': \a";
cin >> user_answer;
if (user_answer == 'y')
{
cout << "I figured it out! Your number is " << max_val << "!\n";
keep_window_open("~");
return 0;
}
else if (user_answer == 'n')
{
cout << "I figured it out! Your number is " << min_val << "!\n";
keep_window_open("~");
return 0;
}
else
{
cout << "That doesn't make sense.";
keep_window_open("~");
return 0;
}
}
cout << "Question " << i << ": Is the number >= " << quest_number << "? Answer yes or no by typing 'y' or 'n': \a";
cin >> user_answer;
if (user_answer == 'y')
{
min_val = quest_number;
cout << "\nTest: the question number = " << quest_number << "\n";
quest_number = min_val + (max_val - min_val) / 2;
cout << "Test: the question number is now = " << quest_number << "\n";
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
}
else if (user_answer == 'n')
{
max_val = quest_number - 1;
cout << "\nTest: the question number = " << quest_number << "\n";
quest_number = min_val + (max_val - min_val) / 2;
cout << "Test: the question number is now = " << quest_number << "\n";
cout << "Test: min_val = " << min_val << ", max_val = " << max_val << ", i = " << i << "\n\n";
}
else
{
cout << "There was an issue with your input.\n";
keep_window_open("~");
return 0;
}
}
}