while loop doesn't loop in c++ - c++

So i just started C++ yesterday, I had a fair bit of java experience so that be the cause idk,
I try to run this code and for some reason the while loop isn't looping, i tried changing the if break statement from ask==false to ask=false, that just ends up with an infinite loop without even taking user input.
Here's the code:
#include <iostream>
#include <math.h>
using namespace std;
int main(){
double raduis;
const double pi = 3.14;
bool ask;
while(true){
cout << "Enter the raduis of the circle:"<< endl;
cin >> raduis;
double circ = 2*pi*raduis;
double area = pi*pow(raduis,2);
cout << "The Circumference of the circle is: "<< circ <<endl;
cout << "The Area of the circle is: "<< area<<endl;
cout <<"Would you like to run again?"<< endl;
cin >> ask;
if(ask==false){
break;
}
}
}
I've tried changing the bool to a char value with "y" or "n" values but to no avail nothing works.
Edit: Okay so I've solved the problem, as per #zdf 's suggestion I entered cin >> boolalpha >> ask; and it works perfectly now.

Call clear on cin before the input and make sure the input is only 0 or 1,
From cppreference:
If the type of v is bool and boolalpha is not set, then if the value to be stored is ​0​, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.

Related

Code breaks after anwser with a dot and skips the rest of the code

If i don't use dots like 1.5 it will break but if it's whole number like 15 it works perfectly
I tried to looking for it in the internet but didn't find the fix it
#include <iostream>
using namespace std;
int main()
{
int n,sk,i,a,p,b,c;
int kiek=0;
cout << "insert how many shops did he went to" << endl;
cin >> n;
b=n;
cout << "how many thing did he buy in every shop" << endl;
cin >> p;
c=p;
for(int n=0; b>n; n++)
{
a=0;
for (int i=1; i<=c; i++)
{
cout << "insert "<< i << " product price"<< endl;
cin >> sk;
a=a+sk;
}
cout<< "spent " << a<< " pmoney"<< endl;
}
return 0;
}
it should let me type how much did he spent with every product but if i add a . it skips everything and shows only one
Problem
An integer type cannot store decimal values.
When you execute int sk; cin >> sk; and you enter "1.5", the operator >> will store 1 in sk and leave .5 in the stream. The next time you execute cin >> sk, the stream will try to read the next integer with what is left in the stream, but will fail because "." cannot be converted to an integer, leaving your stream in a 'fail' state. For this point, all cin instructions will fail to read the next integer.
Solution
To fix the problem, I suggest to declare price values as doubles: double a,sk. However, the same problem will occur if you enter an invalid floating point value. I strongly suggest to correctly manage stream errors and react accordingly. You can access the state using rdstate() or its related methods (good, fail, bad, eof).

gauge the rate of inflation for c++

Write a program to gauge the rate of inflation for the past year. The program asks for the price of an item (such as a hot dog or a 1-carat diamond) both one year ago and today. It estimates the inflation rate as the difference in price divided by the year-ago price. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the rate of inflation. The inflation rate should be a value of type double giving the rate as a percent, for example 5.3 for 5.3 percent.
Your program must use a function to compute the rate of inflation. A program which does not use a function will be awarded a score of zero, even if all tests pass.
I want to repeat the loop, but no wonder I input Y or N, the loop will also repeat. Suppose the loop should repeat when I input 'Y' or 'y'. Can anyone tell me what's wrong with my code?
#include <iostream>
#include <cmath>
using namespace std;
double calculate_inflation(double, double);
int main()
{
double yearAgo_price;
double currentYear_price;
double inflation_Rate;
char again;
do{
cout << "Enter the item price one year ago (or zero to quit) : " << endl;
cin >> yearAgo_price;
cout << "Enter the item price today: " << endl;
cin >> currentYear_price;
cout.setf(ios::fixed)
cout.setf(iOS::showpoint);
cout.precision(2);
inflation_rate=calculate_inflation(yearAgo_price, currentYear_price);
cout << "The inflation rate is " << (inflation_rate*100) << " percent." << endl;
cout << "Do you want to continue (Y/N)?" << endl;
cin >> again;
}while((again =='Y') || (again =='y'));
return 0;
}
double calculate_inflation (double yearAgo_price, double currentYear_price)
{
return ((currentYear_price-yearAgo_price)/ yearAgo_price);
}
while((again='Y') || (again='y'));
should be
while((again=='Y') || (again=='y'));
You have mistaken assignment for comparison operator. Those are different in C and C++.
The effect of your code is that Y or y is assigned to again and the new value is returned. That char is non-zero so converts to true. Thus, true is returned, and the loop turns endless.
Edit:
How you could've found it out yourself with a debugger:
The loop appears to be endless thus we need to check its condition variable. So, place a watch on the again variable and see it change when the loop condition is being evaluated. Problem found.
while ((again='Y') || (again='y') does not do what you think it does. You are assigning to the again variable.
What you want to do is use the == operator to compare again to either 'Y' or 'y'.

checking if entered value is float, clearing cin

I have tried a few different variations of this code and I can't seem to get it right. I am pretty new to c++ yet so that might explain it. This code is part of a simple calculator. It basically asks the user to enter two numbers (they can be floats) and then asks the user for a mathematical operator and then does the operation. If a user enters something that's not a number and then enters a number when asked to enter a number again from the if statement the console prints "-9.25596e+061". This is the code:
#include "stdafx.h"
#include <iostream>
#include <cctype>
using namespace std;
double getUserInput()
{
//Make double, assign double, return double if number
double dUserInput;
//checks if it failed to cin
if (!(cin >> dUserInput))
{
//statement is true
cin.clear();
cin.ignore(99999, '\n');
cout << "You did not enter a number, please try again: ";
getUserInput();
}else
//statement if false
cout << "Number entered"; //for debugging purposes
return dUserInput;
}
You missed to add return in the recursive call to getUserInput.
Change the line
getUserInput();
to
return getUserInput();
Update
You can change the function to a non-recursive version.
double getUserInput()
{
//Make double, assign double, return double if number
double dUserInput;
//checks if it failed to cin
while (!(cin >> dUserInput))
{
cin.clear();
cin.ignore(99999, '\n');
cout << "You did not enter a number, please try again: ";
}
cout << "Number entered"; //for debugging purposes
return dUserInput;
}

How to make the user type a value instead of storing a constant value?

I have made a simple program in C++ and this is the code:
#include <iostream>
using namespace std;
int main()
{
int number;
int square;
number = 5;
square = number * number;
cout << "The square is ";
cout << square;
return 0;
}
what it does is basically taking the integer "5" and get the square value on the screen and so on...
my question is:
how can I make the program take any value from the user instead of storing a value in the memory?
than Q.
Your code makes use of cout to print. C++ makes cin available for input from the console:
int x;
cin >> x;
"An example is worth a thousand words..."
Well cout takes some var. from memory and prints it out on the screen, right?
Well, cin does the exact opposite, it takes in some value from the keyboard and puts it in your memory..
You have to take in the value with the help of cin command, like this:
int a; //lets say you have a variable
cout << "Enter a value here: "; //prompts the user to enter some number
cin >> a; //this line will allow the user to enter some value with the keyboard into this var.
int square = a * a;
cout << "The square is: " << square;
Hope it helps...
Just replace:
number = 5;
with:
cout << "What's the number? ";
cin >> number;
You already know how to use cout to generate output, this simply uses cin to retrieve input.
Keep in mind that, while this may be okay for small test programs or learning, data input in real programs tends to be a little more robust (such as if you enter the string xyzzy when it's trying to input an int variable).

C++ cin positive integers only

This is my first time on Stackoverflow.
I was making a program to find out MPG for a car. I was wondering how can I make the cin statement only accept positive integers only? and also, if you do enter a invalid input, can you reset it? I am not sure if that makes sense. I didn't have to do this for class. I was just curious on how to do it. Here is the code.
#include <iostream>
using namespace std;
int main()
{
double tank, miles, mpg;
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
mpg = (miles)/(tank);
cout << "Your vehicle recieves " << mpg << " miles per gallon\n" << endl;
system ("pause");
return 0;
}
iostreams are not a toolkit for building a complex UI. Unless you want to write your own rather complex stream to wrap the usual stream, there is no way you are going to get it to either (a) only accept positive integers or (b) interact politely with a user who types in something else.
You should just read lines from cin, and print your own error prompts and such after you look at what you get.
cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
do
{
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
} while (tank <= 0 && ((int)tank != tank));
do
{
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;
} while (miles <= 0 && ((int)miles != miles));
If you do this after running the statements it will rerun them if the answer is 0 or lower or is not an integer. If you make the variables ints instead of doubles then you can remove the "&& ((int)miles == miles)" part of the while statement.
Still, there are a couple of standard ways to do it in a command line environment.
You could trap the cin statement in a loop that doesn't release until a valid input has been entered. This is the "standard" way to validate CLI input, not just signed numbers.
do
{
cout << "\nPlease enter...";
cin >> tank;
}
while (tank < 0)
The condition in the while statement is the place to validate the data. You can also make an if statement to explain why the input is invalid.
The other way is to simply force the value to be positive, by simply going tank = fabs(tank);, which takes the absolute value (i.e. positive) of the tank variable.
So this is my code for an infinite loop
1: So main will call the "Get_number()" function
2: Get number will accept an int from the user
3(A): If int is greater than 0, go into loop
3(B): Else, display to user "Invalid Input" and then call the function
"Get_number()" again creating an infinite loop until the user
enters a value greater than 0
#include <iostream> // Access the input output stream library
#include <fstream> // Access to the fstream library (used to read and write to files)
#include <chrono> // Needed to access "std::chrono_literals"
#include <thread> // Needed to access "namespace std::this_thread"
using std::fstream; // this will allow us to use the fstream (we'll be able to read and write to files)
using std::ios; // needed for iostream (used to be able to tell fstream to read and/or write to a file and that it's reading/writing a binary file)
using std::cout; // need this statment to access cout (to display info to user)
using std::cin; // need this statment to access cin (to gather info from user)
using std::endl; // need this statment to access endl (will end the line)
using namespace std::this_thread; // This will allow me to use "Sleep_For" or "Sleep_Until"
using namespace std::chrono_literals; // This will allow the use of measurements of time such as ns, us, s, h, etc.
//Prototypes***************************************************************************************************
void shellSort(int read[], int readLength); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Get_number();
void Write_to_file(int user_input_of_how_many_random_numbers_to_generate); //Making Prototype (Declaring our function) so that compiler knows not to worry about it
void Read_from_file(int user_input_of_how_many_random_numbers_to_generate);//Making Prototype (Declaring our function) so that compiler knows not to worry about it
//*************************************************************************************************************
void main()
{
Get_number();
system("pause>>void"); // will let the console pause untill user presses any button to continue
}
/**************************************************************************************************************
* Purpose: This function will gather a positive integer from the user and use it to generate that many
* random numbers!
*
* Precondition: None
*
*
* Postcondition:
* Would've gathered the number of random numbers the user wanted to generate and then gone into the
* Write_to_file and Read_from_file function
*
**************************************************************************************************************/
void Get_number()
{
int user_input_of_how_many_random_numbers_to_generate = 0; //make variable that will accept the int value the user wants to generate random numbers
cout << "Please Enter A Number Greater Than Zero:" << endl; // displays to user to enter a number greater than zero
cin >> user_input_of_how_many_random_numbers_to_generate; // will accept the value the user inputted and place it in the "user_input_of_how_many_random_numbers_to_generate" variable
system("cls"); // Will clear the screen
if (user_input_of_how_many_random_numbers_to_generate > 0) // if user input is greater than zero, enter this
{
Write_to_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Write_to_file" function
Read_from_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Read_from_file" function
}
else // else enter this
{
cout << "invalid input!" << endl; // display to user "invalid input"
sleep_for(2s); // system will pause for 2 seconds allowing the user to read the message of "invalid input"
system("cls"); // console will be cleared
Get_number(); // Get_number function will be entered creating an infinate loop untill the user's input is valid!
}
}
Instead of
cin >> miles;
Try
while ( (cin >> miles) < 0 )
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
That will repeat the question until the input is positive. You can do that for the rest of the questions too.
Note that input streams are not intended for input filtering. You have to provide your own logic for that.