With this code:
#include <iostream>
#include <iomanip>
using namespace std;
//Functions
int power(int base,int exp);
double energy(int z, int n);
//Main
int main() {
const double E0(13.6),hce(1.24E-6),e(1.6E-19);
int n1,n2,z;
double E;
cout << "**************************************" << endl;
cout << "Welcome to the energy level calculator\n" << endl;
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
while(cin.fail()||z<1||n1<1||n2<1){
cout << "\n\n\n\n\nPlease enter non-zero integers only, try again\n\n\n\n\n\n" << endl;
cout << "**************************************" << endl;
cin.clear();
cin.ignore();
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
}
etc...
The program is only allowed to accept Integers
If i enter a decimal, such as 1.2 the program rejects the 1. but uses the 2 as z when it should be asking for input from the keyboard?
Can anyone help?
Since you asked for an explanation, when you enter 1.2
cin >> z; //Successfully reads '1' into 'z'
cin >> n1; //Fails to read '.' into 'n1'. '.' remains the first character in the stream.
cin >> n2; //Fails to read '.' into 'n2'. '.' remains the first character in the stream.
You then loop back to the beginning of your loop.
cin.clear(); //clears the fail flag from the two previous failed inputs
cin.ignore(); // ignores the '.'
cin >> z; //Reads '2' into 'z'. The stream is now empty.
The program then blocks on cin >> n1 waiting for more characters to be placed in the stream.
After each input, you should see if the input failed.
cin>>n1;
if(cin.fail())
cin.ignore();
Related
First of all I am new to C++, can you guys help me with validating if value enter is an integer? And if my while statement in int(main) can be replace with a function.
#include <iostream>
using namespace std;
int validateNumb (int numb, int lim){
//takes a num, limit and checks if number is within limit
while (numb>=lim) { //if outside limit
cout << "Invalit input, try again with number (less than " << lim <<"): ";
cin >> numb; //assign user input value
}
cout << "Your integer is: " << numb << "\n\n"; //display input value
return numb;
}
int main() {
//variables
int num1, num2, num3, sum;
int limnum1, limnum2, limnum3;
//Welcome message
cout << "Hello & Welcome to E&M Ls1\n\n\n";
//First Number
cout << "Please Define the limit for First integer: ";
while (!(cin >> limnum1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the First Integar that is (less than " << limnum1 << "): ";
while (!(cin >> num1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num1 = validateNumb(num1, limnum1); //check condition
//Second Number
cout << "Please Define the limit for Second integer: ";
while (!(cin >> limnum2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Second Integar that is (less than " << limnum2 << "): ";
while (!(cin >> num2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num2 = validateNumb(num2, limnum2); //check condition
//Third Number
cout << "Please Define the limit for Third integer: ";
while (!(cin >> limnum3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Third Integar that is (less than " << limnum3 << "): ";
while (!(cin >> num3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num3 = validateNumb(num3, limnum3); //check condition
//Sum for num1+num2+num3
sum = num1+num2+num3;
cout << "Sum of " << num1 <<" & " << num2 <<" & " << num3 <<" is: " << sum << ""; //display input value
cout<<"_______________________"<<endl;
cout<<"Thank you & Goodbye"<<endl; //end of the program
return 0;
}
bool is_integer(float k)
{
return std::floor(k) == k;
}
This solution should work for all possible values of k. I am pretty sure this is a case where you can safely compare floats using ==.
and yes your main can be broken into functions, maybe something like...
int getFirstNumber(){
int num =0;
// copy your code to get the first number
return num;
}
int getSecondNumber(){
int num =0;
// copy your code to get the second number
return num;
}
int getThirdNumber(){
int num =0;
// copy your code to get the thirdnumber
return num;
}
int sum(int a,int b,int c){
return (a+b+c);
}
int main(){
int a,b,c,d =0;
a = getFirstNumber;
b = getSecondNumber;
c = getThirdNumber;
d = sum(a,b,c);
return 0;
}
EDIT: I see you want to check if the number is in a valid range...
here:
// Returns true if x is in range [low..high], else false
bool inRange(unsigned low, unsigned high, unsigned x)
{
return ((x-low) <= (high-low));
}
So for my code, it ask's the user to input a number for x but i happened to fat fingered it and i typed in (1 2) with a space between 1 and 2 and my code directly went to outputting my x and y even thought it didn't ask for y coordinates yet.
#include <iostream>
using namespace std;
int main(){
double x, y;
cout << "Enter x coordinate: ";
cin >> x;
while (!cin.good() ) {
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Enter your x coordinate";
cin >> x;
}
cout << "Enter y coordinate: ";
cin >> y;
while(!cin.good()){
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Enter your y coordinate";
cin >> y;
}
cout << "You x coordinate is at: " << x << ", Your y coordinate is at: " << y ;
return 0;
}
using the cin you get input eather by entering the data and pressing enter or by seperting by spaces, so:
cin >> var;
cin >> var2;
can get input eather by entering var1's data and pressing enter and then entering var2's data and pressing enter or by entering data for both var1 and var2 seperated by spaces and if the data is valid it would accept it.
notice that when the data it !cin.good() it would start the cin again
You wrote 1 2 into the stream. cin >> x; reads and removes the 1. The 2 stays in the stream. cin only blocks if the stream is empty.
I have no idea how i would reject invalid inputs for the exams and assignments (valid numbers are 0.00 - 100.00). but i also need to give the user one more chance to enter a valid input. so if they put in two invalid inputs in a row for the same variable it tells the user that they need to restart the program and prevent it from running. Im new to programming so im not very good at this.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main ()
{
float exam_1;
float exam_2;
float exam_3;
float assignment_1;
float assignment_2;
float weighted_exam = .1667;
float weighted_assignment = .25;
float min_score = 0.00;
float max_score = 100.00;
string name;
cout << "Please enter student name <First Last>: "; // this will ask for the students first and last name
getline(cin, name);
cout << "\n";
cout << "\t Be sure to include the decimal point for scores.\n";
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cout << "\t For example: 80.50 \n";
cout << "\n";
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
cout << "Please enter your assignment 1 score: ";
cin >> assignment_1;
cout << "Please enter your assignment 2 score: ";
cin >> assignment_2;
cout << endl;
cout << "-" << "OUTPUT" << "-\n";
return 0;
}
You can do like this:
do{
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cin >> exam_1;
while(exam_1 < 0.0 || exam_1>100.0);
Repeat this to all inputs
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
To
auto ReadExamScore = [](auto& ex, char c)
{
cout << "Please enter your exam " << c << " score: ";
for (int i = 0; i < 2; i ++)
{
if (cin >> ex)
{
if (ex>= 0.0 && ex <= 100.00)
return true;
}
cout << "Please enter a valid exam score" << endl;
}
cout << "Press any key to exit..." << endl;
getchar();
exit(0);
};
ReadExamScore(exam_1,'1');
ReadExamScore(exam_2,'2');
ReadExamScore(exam_3,'3');
This question already has answers here:
Using getline(cin, s) after cin [duplicate]
(13 answers)
Closed 7 years ago.
I'm relatively new to C++, but not to programming, and I'm confused as to why I am having this very strange issue with a while loop in my C++ program.
while (runUserInputLoop)
{
displayMenu();
cout << "Enter the number that corresponds with your choice from the menu: ";
getline(cin, menuLoopChoice);
if (menuLoopChoice == "1")
{
cout << "Enter mean: ";
cin >> mean;
cout << "Enter z-score: ";
cin >> z;
cout << "Enter standard deviation: ";
cin >> stDev;
cout << "Enter sample size: ";
cin >> n;
oneSampZInt(mean, z, stDev, n);
}
else if (menuLoopChoice == "2")
{
cout << "Enter mean: ";
cin >> mean;
cout << "Enter t-score: ";
cin >> t;
cout << "Enter standard deviation: ";
cin >> stDev;
cout << "Enter sample size: ";
cin >> n;
oneSampTInt(mean, t, stDev, n);
}
else if (menuLoopChoice == "3")
{
cout << "Enter mean for first sample: ";
cin >> mean1;
cout << "Enter mean for second sample: ";
cin >> mean2;
cout << "Enter standard deviation for first sample: ";
cin >> stDev1;
cout << "Enter standard deviation for second sample: ";
cin >> stDev2;
cout << "Enter z-score: ";
cin >> z;
cout << "Enter size of first sample: ";
cin >> n1;
cout << "Enter size of second sample: ";
cin >> n2;
indepMeansZInt(mean1, mean2, stDev2, stDev1, n1, n2, z);
}
else if (menuLoopChoice == "4")
{
cout << "Enter mean for first sample: ";
cin >> mean1;
cout << "Enter mean for second sample: ";
cin >> mean2;
cout << "Enter standard deviation for first sample: ";
cin >> stDev1;
cout << "Enter standard deviation for second sample: ";
cin >> stDev2;
cout << "Enter t-score: ";
cin >> t;
cout << "Enter size of first sample: ";
cin >> n1;
cout << "Enter size of second sample: ";
cin >> n2;
indepMeansTInt(mean1, mean2, stDev2, stDev1, n1, n2, t);
}
else if (menuLoopChoice == "5")
{
cout << "Enter sample proportion: ";
cin >> p;
cout << "Enter sample size: ";
cin >> n;
cout << "Enter z-score";
cin >> z;
onePropZInt(p, n, z);
}
else if (menuLoopChoice == "6")
{
cout << "Enter proportion from sample one: ";
cin >> p1;
cout << "Enter proportion from sample two: ";
cin >> p2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter z-score";
cin >> z;
twoPropZInt(p1, p2, n1, n2, z);
}
else if (menuLoopChoice == "7")
{
cout << "Enter chi-sqaured right value: ";
cin >> chiSqrdRight;
cout << "Enter chi-sqaured left value: ";
cin >> chiSqrdLeft;
cout << "Enter sample variance: ";
cin >> variance;
cout << "Enter sample size: ";
cin >> n;
chiSqrdInt(chiSqrdRight, chiSqrdLeft, variance, n);
}
else if (menuLoopChoice == "8")
{
cout << "Enter mean of differences: ";
cin >> DBar;
cout << "Enter standard deviation of differences: ";
cin >> SD;
cout << "Enter number of matched pairs: ";
cin >> n;
cout << "Enter t-score: ";
cin >> t;
matchedPairsTInt(DBar, SD, n, t);
}
else if (menuLoopChoice == "A" || menuLoopChoice == "a")
{
cout << "Enter population mean: ";
cin >> mean1;
cout << "Enter sample mean: ";
cin >> mean2;
cout << "Enter population standard deviation: ";
cin >> stDev;
cout << "Enter size of sample: ";
cin >> n;
cout << "Enter z-score: ";
cin >> z;
oneSampZTest(mean1, mean2, stDev, n, z);
}
else if (menuLoopChoice == "B" || menuLoopChoice == "b")
{
cout << "Enter mean of sample one: ";
cin >> mean1;
cout << "Enter mean of sample two: ";
cin >> mean2;
cout << "Enter standard deviation of population one: ";
cin >> stDev1;
cout << "Enter standard deviation of population two: ";
cin >> stDev2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter z-score: ";
cin >> z;
twoSampZTest(mean1, mean2, stDev1, stDev2, n1, n2, z);
}
else if (menuLoopChoice == "C" || menuLoopChoice == "c")
{
cout << "Enter population mean: ";
cin >> mean1;
cout << "Enter sample mean: ";
cin >> mean2;
cout << "Enter sample standard deviation: ";
cin >> stDev;
cout << "Enter size of sample: ";
cin >> n;
cout << "Enter t-score: ";
cin >> t;
oneSamptTest(mean1, mean2, stDev, n, z);
}
else if (menuLoopChoice == "D" || menuLoopChoice == "d")
{
cout << "Enter mean of sample one: ";
cin >> mean1;
cout << "Enter mean of sample two: ";
cin >> mean2;
cout << "Enter standard deviation of sample one: ";
cin >> stDev1;
cout << "Enter standard deviation of sample two: ";
cin >> stDev2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter t-score: ";
cin >> t;
twoSamptTest(mean1, mean2, stDev1, stDev2, n1, n2, t);
}
else if (menuLoopChoice == "E" || menuLoopChoice == "e")
{
cout << "Enter the population proportion: ";
cin >> p1;
cout << "Enter the sample proportion: ";
cin >> p2;
cout << "Enter the sample size: ";
cin >> n;
cout << "Enter the z-score: ";
cin >> z;
onePropZTest(p1, p2, n, z);
}
else if (menuLoopChoice == "F" || menuLoopChoice == "f")
{
cout << "Enter sample proportion one: ";
cin >> p1;
cout << "Enter sample proportion two: ";
cin >> p2;
cout << "Enter the x value of proportion one: ";
cin >> x1;
cout << "Enter the x value of proportion two: ";
cin >> x2;
cout << "Enter the size of sample one: ";
cin >> n1;
cout << "Enter the size of sample two: ";
cin >> n2;
cout << "Enter the z-score: ";
cin >> z;
twoPropZTest(p1, p2, x1, x2, n1, n2, z);
}
else if (menuLoopChoice == "q" || menuLoopChoice == "Q")
{
runUserInputLoop = false;
}
}
On the first iteration through the loop, everything works fine. However, on all subsequent iterations, the loop seems to iterate once, without any input, and then again, allowing me to enter input once again. So essentially, there is an extra iteration that causes it to perform this portion of the while loop twice:
displayMenu();
cout << "Enter the number that corresponds with your choice from the menu: ";
getline(cin, menuLoopChoice);
Here is a picture of how it looks in the console: . The crudely circled portion is the "ghost iteration." I feel like it should be something simple, but I'm not extremely familiar with C++ yet, so I'm stumped. The full code for the program is available here if necessary.
std::istream::operator>> reads characters from the stream until it encounters whitespace (such as an end-of-line character), but it leaves the whitespace character in the stream, so the next read will see it. That's fine if the next read is an operator>>, since it will skip over leading whitespace, but std::getline() just reads until it sees the delimiter character ('\n' by default). Since the previous call to operator>> left a '\n' as the next character in the stream, std::getline() sees it, and returns immediately. To get around this, you can call std::cin.ignore() at the end of your loop to discard the '\n' that's been left in the input stream.
#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
int main()
{
float startTemperature;
float endTemperature;
float loopTemperature;
float stepSize;
float i;
float numberOne;
cout << "Please enter a start temperature: " << endl;;
cin >> startTemperature;
while(!(cin >> startTemperature)){
cin.clear();
cout << "Invalid input. Try again: ";
}
cout << "Please enter an end temperature: ";
cin >> endTemperature;
while(!(cin >> endTemperature)) {
cin.clear();
cin.ignore(256, '\n');
cout << "Invalid temperature. Please try again: ";
}
cout << "Please enter a step size: ";
cin >> stepSize;
while(!(cin >> stepSize)) {
cin.clear();
cin.ignore(256, '\n');
}
for(i = startTemperature; i < endTemperature; i += stepSize) {
if(i == startTemperature) {
cout << "Celsius" << endl;
cout << "-------" << endl;
cout << startTemperature << endl;
loopTemperature = startTemperature + stepSize;
}
loopTemperature += stepSize;
if(loopTemperature > 20) {
break;
}
cout << loopTemperature << endl;
}
}
Hi, The problem with this code is that I have to input the value of the temperature twice. I have looked at other answers and I think it is something to do with the cin buffer but I don't know exactly what is wrong.
In the line
cin >> startTemperature; // <---problem here
while(!(cin >> startTemperature)){
cin.clear();
cout << "Invalid input. Try again: ";
}
You are taking input once, then again in the loop. That's is why you had to give input twice.
Just remove first input line, same for endTemparature and stepSize.
You're asking for input before the while loop, then again in the loop condition statement. Change the condition in your while statement to
while(!cin){
//error handling you already have
cin>>startTemperature; //endTemperature respectively
}
It's not only for the temperature but rather for every input. Change your code to the one below:
cout << "Please enter a start temperature: " << endl;;
while (!(cin >> startTemperature)){
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid input. Try again: ";
}
cout << "Please enter an end temperature: ";
while (!(cin >> endTemperature)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid temperature. Please try again: ";
}
cout << "Please enter a step size: ";
while (!(cin >> stepSize)) {
cin.clear();
cin.ignore(std::numeric_limits<int>::max(), '\n');
cout << "Invalid step size. Please try again: ";
}
Reason:
You had redundant cin calls. Also use std::cin.ignore(std::numeric_limits<int>::max(), '\n'); instead of arbitrary number 256.