Trying to step out of this loop [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm sorry if the code looks sloppy. I've only learned some loops and if checks so far in the book. I would like to code to step out of the loop. I've tried using break and then I tried with this loop.
#include "std_lib_facilities.h"
using namespace std;
int main()
{
double smallest = 0;
double largest = 0;
double x = 0;
string measure = " ";
double sum = 0;
vector<double> meters;
bool leave = false;
if (!leave)
{
while(cin>>x>>measure)
{
if (x < largest)
smallest = x;
else
largest = x;
if ( x == 'x')
leave = true;
cout << "You typed " << x << " Smallest number so far: " << smallest << " Largest number so far: " << largest << endl;
if(measure == "in") //inches
{
cout << "You wanted inches? : " << x << " inches" << endl;
cout << "That also happens to be : " << x * 2.54 << " cm" << endl; // inches to cm
sum += x * 0.0254;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "cm") //centimeter
{
cout << "You wanted centimeters? : " << x << " centimeter" << endl;
cout << "That also happens to be : " << x / 100 << " m" << endl; // inches to cm
sum += x / 100;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "f") //feet
{
cout << "You wanted feet? : " << x << " feet" << endl;
cout << "That also happens to be : " << x * 12 << " inches" << endl; // inches to cm
sum += x * 0.3048;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "m") //meters
{
cout << "You wanted meters? : " << x << " meters" << endl;
cout << "That also happens to be : " << x * 100 << " cm" << endl; // inches to cm
sum += x;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else
{
cout << "error invalid measurement. " << endl;
keep_window_open();
}
}
}
for(int i = 0; i<meters.size(); ++i)
cout << meters[i];
keep_window_open();
}

You check the leave condition before the loop, which will of course not work very well. You should check it inside the loop.
It can simplest be put into the actual loop condition:
while(!leave && cin >> x >> measure) { ... }
It seems like you want the input to be either a number and a string, or just a character. That will not work as the variable x is a double and can't handle strings or characters being input. You should actually get a warning about using a double as a character (the x == 'x' comparison).
It might be better to do something like
std::string input;
while (std::getline(std::cin, input))
{
std::istringstream is(input);
// Try to get a number and a string
if (is >> x >> measure)
{
// Got it, do stuff here...
}
else
{
// Input was not a number and a string, try to get a character
char ch;
if (is >> ch && ch == 'x')
break; // Exit loop
else
{
std::cout << "Wrong input, have to be a number and a string, or 'x' to exit\n";
}
}
}
The problem you're having with the program exiting abruptly is most likely because of this. When the input statement std::cin >> x >> measure can't read the input as a number, it will leave the character in the input buffer, so keep_window_open (which I guess reads a string or a character) will get that 'x' and exit immediately.

Related

Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0

Console bar charts and division of results based on highest? | 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;
}

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

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

C++ Factor Program: Outputting Number of Factors Given

I am writing a simple program that finds the factors of a list of integers through Linux Redirection. I am almost done, but I am stuck on one part. Here is my program so far:
#include<iostream>
using namespace std;
int main()
{
int counter = 0;
int factor;
cin >> factor;
while (cin)
{
if (factor < 0)
break;
cout << "The factors of " << factor << " are " << endl;
for(int i=factor; i>=1; i--)
if (factor % i == 0)
{
counter++;
cout << i << endl;
}
cout << "There are " << " factors." << endl;
cout << endl;
cin >> factor;
}
return 0;
}
Now the problem I have is in the line " cout << "There are " << " factors." << endl; ". I'm not sure how to calculate the number of factors output by the program.
For example:
The factors of 7 are
1
7
There are 2 factors.
How would I go about calculating and outputting the "2" in this example.
Help is greatly appreciated.
Instead of
cout << "There are " << " factors." << endl;
use
cout << "There are " << counter << " factors." << endl;
If you do that, you have to move the line where you define counter.
Instead of it being the first line in main, it needs to be moved to be the first line in the while loop.