Having to input value twice to work C++ - c++

#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.

Related

validating if value enter is an integer

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

C++ User input validation not working properly

I have this code that asks for a number input and stores it in a variable. I'm trying to do validation on the input but it's behaving weirdly.
#include <iostream>
using namespace std;
float coursework_mark;
float exam_mark;
float module_mark;
int main() {
//COURSEWORK INPUT WITH VALIDATION
cout << "Please enter your coursework mark: ";
while(!(cin >> coursework_mark)){
cin.clear();
cin.ignore(1000, '\n');
cout << "Invalid data type, please enter valid coursework mark: ";
}
while (coursework_mark < 0 || coursework_mark > 100) {
cout << "Out of range, please enter valid coursework mark: ";
cin >> coursework_mark;
}
//EXAM MARK INPUT WITH VALIDATION
cout << "Please enter your exam mark: ";
while(!(cin >> exam_mark)) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Invalid data type, please enter valid exam mark: ";
}
while (exam_mark < 0 || exam_mark > 100) {
cout << "Out of range, please enter valid exam mark: ";
cin >> exam_mark;
}
//Coursework capping
if (coursework_mark > exam_mark * 2) { coursework_mark = exam_mark * 2;}
//Calculate Module mark
module_mark = (coursework_mark* 0.4) + (exam_mark* 0.6);
//Output results
cout << coursework_mark << endl;
cout << "Your module mark is " << module_mark << endl;
if (module_mark >= 50) {
cout << "Congratulations you have passed!" << endl;
} else if (module_mark < 50) {
cout << "Unfortunately, you have not passed" << endl;
}
}
If user inputs '45kuefggf' the number 45 gets stored as the coursework mark and the code hits the line cout << "Out of range, please enter valid exam mark: ";. I have no idea why it's doing this, how do I make it so that it check if the user input a valid data type?
Instead of
while(!(cin >> coursework_mark)){
you should use std::getline
std::getline(std::cin, coursework_mark);
https://en.cppreference.com/w/cpp/string/basic_string/getline
bool has_only_digits(string s){
return s.find_first_not_of( "0123456789" ) == string::npos;}
This method is the simplest way I found to check if a string contains a number. So if it returns true the string has only digits else it contains more than just digits.
If the statement is false you can then clear the cin like you have done above.

While loop not breaking, using cin.ignore and cin.clear() to verify input

I'm trying to use a loop to verify that the input grade is an integer, but when I intentionally input a char, the program does nothing. It only starts a newline upon pressing enter.
void fillvector(vector<student>& parameter)
{
string newname;
int newgrade;
int number;
cout << "How many students are in your class: ";
cin >> number;
for (int i = 0; i < number; i++)
{
cout << endl << "Enter student name: ";
while (1)
{
cin >> newname;
cout << "Enter student grade: ";
cin >> newgrade;
if (cin.fail())
{
cout << endl << "Grade must be an integer value, try again.";
cin.clear();
cin.ignore(INT_MAX);
i--;
break;
}
else
{
student student(newname, newgrade);
parameter.push_back(student);
break;
}
}
}
cout << endl;
}
cin.ignore(INT_MAX);
This will make cin ignore any further characters you enter up to MAX_INT..
What you wanted is to ignore up-to the next newline:
cin.ignore(INT_MAX, '\n');
Besides, there is no point in making a while(1) loop that will break in all paths in the first iteration. You can remove that inner loop.

Need help to figure why my array its not saving an input?

so this is a ship's database and my problem is that I have to check if the user enter an integer, but when the program saves registry to the array and I show the result the registry variable where the user puts the number its an scramble of numbers
int tester1 = 0;
cout << "What is the registry of the ship?: ";
cout << " >>";
if (cin >> tester1)
{
tester1 >> array[counter].registry;
cin.clear();
cin.ignore(1000, '\n');
}
else
{
while (!(cin >> tester1))
{
cout << "Please enter an integer!!" << endl;
cout << " >>";
cin >> tester1;
cin.clear();
cin.ignore(1000, '\n');
}
}
cin>>tester1;
while(!cin) {
cin.clear();
cin.sync();
cout << "Please enter an integer!!" << endl;
cout << " >>";
cin>>tester1;
}
array[counter].registry=tester1;

Why cant i reject Decimals? (C++)

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();