Here is an excerpt of my code, where the problem lies.
long long user_largest_plus;
long long user_largest_minus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus;
//cout << endl;
// cout << "Input the largest-1 in decimal: " << endl;
cin >> user_largest_minus;
cout << endl;
cout << "In decimal plus: " << user_largest_plus;
cout << endl;
cout << "In decimal minus: " << user_largest_minus;
As soon as I input 9223372036854775808 to user_largest_plus, the execution would terminate. That is, I wouldn't be able to input for user_largest_minus.
I am using Code::Blocks, MinGW compiler.
Is it because I just overflowed the variable, and the error triggered this termination. Any work around?
By the way, that number is 2^63 - 1, maximum number that I can store.
Thanks
Try replacing
cin >> user_largest_plus;
with
if( !( cin >> user_largest_plus ) ) {
user_largest_plus = 0;
cin.clear();
cout << "Bad input. Using zero instead\n";
}
When the input text is not a valid long long, two interesting things happen:
user_largest_plus is never set, and
the bad bit is set in cin.
The provided code sets some value to user_largest_plus to avoid undefined behavior, and clears the bad bit, so cin can still be used.
Assuming it is because the entered number is to big (and to prevent bugs when the user enters APPLE as the size, you should do something like this:
string user_largest_plus_string;
long long user_largest_plus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus_string;
user_largest_plus = atoi(user_largest_plus_string.c_str());
if (user_largest_plus == 0)
throw std::runtime_error("User entered something besides a number!");
cout << "largest+1 is now " << user_largest_plus << "." << endl;
Related
So, I'm trying to make a basic C++ program that converts Base 10 -> Base 16
while(true){
int input;
cout << "Enter the base 10 number\n";
cin >> input;
cout << "The hex form of " << input << " is: ";
int decimal = input;
cout << hex << uppercase << decimal << "\n";
decimal = NULL;
input = NULL;
Sleep(3000);
}
And on the first run through it works. For example, if I enter 7331 I get:
The hex form of 7331 is 1CA3
But if I try it a second time (with the same input) I get:
The hex form of 1CA3 is 1CA3
I can try this with any integer input and it works fine for the first run through but after that it puts the base 16 number in twice.
You need to reset your stream. When you apply std::hex to std::cout, it applies permanently to the stream (std::cout), and you need to reset it. You can simply change your program to this:
cout << "The hex form of " << std::dec << input << " is: ";
your FIX:
cout << "The hex form of "<< dec << input << " is: ";
You could even shorten your code:
while (true)
{
int input;
cout << "Enter the base 10 number: ";
cin >> input;
cout << "The hex form of " << dec << input << " is: ";
cout << hex << uppercase << input << "\n";
Sleep(3000);
}
My program runs the first For loop correctly then skips the Cin's on the 2nd and 3rd cycle. Then when the loop is finished it goes on to calculate the BMI of the first index [0] and does this correctly and gives the right answer but then nothing for the index's 1 and [2] because no information was inputted because the cin's were skipped.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
int main()
{
Patient Patients[3];
for (int i = 0; i < 3; i++) {
cout << "Patient "<< i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << endl << endl;
}
cout << endl << endl;
for (int i = 0; i < 3; i++) {
float BMI = Patients[i].weight / (Patients[i].height *Patients[i].height);
cout << "Patient " << i << " Has A BMI of: " << BMI << endl << endl;
}
return 0;
}
This is the console where you can see after the first loop all the cin's are skipped but the first loop was correctly stored as it couted the BMI of the first index:
You see that you are having an error at the end of the loop. You can see from iterations 2 and 3 that cin is not behaving the same way each time. There are a couple of error state flags that come from ios that will help you see what's going wrong here. See iso::good for details. If you add those checks:
for (int i = 0; i < 3; i++) {
cout << "Patient " << i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << cin.good() << '\n';
cout << cin.eof() << '\n';
cout << cin.fail() << '\n';
cout << cin.bad() << '\n';
cout << endl << endl;
}
What you will see if that cin is no longer good, it is not eof it is fail, and it is not bad. While the fail bit is set, cin will not work. Hence you see the result. Looking at the chart in the link you see this:
Logical error on i/o operation
You were preforming an i/o operation of inserting "true" into a bool. The word true is probably stored as a character array or string, not a boolean. How should cin convert this to a boolean? You need to trap your input and convert it into a bool or switch to use an input that can be explicitly converted into a bool.
For example:
cout << "Is Patient " << i << " Male? (1 for Male, 0 for Female):";
cin >> Patients[i].isMale;
In this case the cin recognizes 1 and 0 as integers and can convert an integer into a boolean. 0 is false, everything else is true. Another option is to let the library do it and use boolalpha. You can read about it here.
This shows a larger issue. What happens if I write "two point five" as the answer to height? In this case we can assume some intelligence on the part of the user, but thinking about things like this will help write more robust code in the future.
You can fix your program in two ways.
Just input "0" or "1" in the male/female question instead of "true" or "false".
Change this line and continue to input "true" or "false":
cin >> boolalpha >> Patients[i].isMale;
Sources:
Cin and Boolean input
http://www.cplusplus.com/reference/ios/boolalpha/
just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
I have a quick question for input verification. I have my loop, and it works for negative numbers, but when I input something like a + sign, it causes an infinite loop. Is there any way to fix it?
cout << "Input Quarter 1 Sales: " << endl;
cin >> quarter1;
while (quarter1 < 0)
{
cout << "Error! Sales Must be a Positive Number!" << endl;
cout << "Please Input a Positive Number" << endl << endl;
cin >> quarter1;
}
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;