specifying a cin value (c++) - c++

say I have:
int lol;
cout << "enter a number(int): ";
cin >> lol
cout << lol;
If I type 5 then it'll cout 5. If I type fd it couts some numbers.
How can I specify the value, like say I only want it an int?

If you type in fd it will output some numbers because those numbers are what lol happens to have in them before it gets assigned to. The cin >> lol doesn't write to lol because it has no acceptable input to put in it, so it just leaves it alone and the value is whatever it was before the call. Then you output it (which is UB).
If you want to make sure that the user entered something acceptable, you can wrap the >> in an if:
if (!(cin >> lol)) {
cout << "You entered some stupid input" << endl;
}
Also you might want to assign to lol before reading it in so that if the read fails, it still has some acceptable value (and is not UB to use):
int lol = -1; // -1 for example
If, for example, you want to loop until the user gives you some valid input, you can do
int lol = 0;
cout << "enter a number(int): ";
while (!(cin >> lol)) {
cout << "You entered invalid input." << endl << "enter a number(int): ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
// the above will loop until the user entered an integer
// and when this point is reached, lol will be the input number

Related

If-Else Statement Returning Same Feedback

So for some reason no matter what I enter into this If-Else statement it returns with a "Program Aborted" as if I entered the wrong requested answers...very confused and I can't seem to find anything relevant enough around the site!
int ch;
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
int ExtraCredit;
if (ch == 'Y' || ch== 'y')
{
cout << "Enter the number of extra credit points: ";
cin >> ExtraCredit
}
else if (ch!='n' || ch!='N' || ch != 'y' || ch != 'Y')
{
ExtraCredit=0;
cout<< Invalid entry. Program Aborted." << endl;
return 0;
}
The issue appears very early:
int ch; // are you sure this should be an int?
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
cin behaves differently on int typed variables than on chars. When you enter "y" or "n" at the keyboard, cin will fail.
You can check whether cin failed by calling its fail() method, like so:
int num;
std::cout << "Enter a number: ";
std::cin >> num;
if (std::cin.fail()) {
std::cout << ":(" << std::endl;
} else {
std::cout << "Your number was " << num << std::endl;
}
ints and chars are separate types, even though they can be compared based on the ASCII value of the char in C++. Because they are defined as separate types, when your code gets to the line cin >> ch and ch is of type int, it waits for something to be entered. The prompt tells the user to enter a char, and they do. The code sees the char, and as it wasn't an int, nothing is read in and the value of ch is correctly determined by your code to be not y, Y, n, or N. If you'd like to cin a char, declare char ch;. If you'd like to have an int, prompt the user to enter a number.

While loop not waiting for user input (while datatype is invalid)

Trying to check if cin obtained valid input (eg - no string or char in int variable), but the while loop gets stuck at an infinite loop and doesn't even wait for user input
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "How many would you like to buy ? ";
int buyAmt;
cin >> buyAmt;
while (!cin) {
cin.clear();
cin >> buyAmt;
cout << "Sorry, you must enter an integer" << endl << endl;
}
}
Expected result:
How many would you like to buy ? fdssd
Sorry, you must enter an integer (asks for usr input here)
Actual result:
How many would you like to buy ? fdssd
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
After applying cin.clear(); you need to consume the wrong input first, before applying cin >> buyAmt; again.
Something like
while (!cin) {
std::string dummy;
cin.clear();
cin >> dummy;
cout << "Sorry, you must enter an integer" << endl << endl;
cout << "How many would you like to buy ? ";
cin >> buyAmt;
}

C++ Program glitch?

I need help debugging my code. So I made a program that adds and subtracts numbers but when I implemented a do-while loop to replay the program, the actual program closes and does not perform the do-while loop and does not replay the program. Is their something wrong with my code?
P.S. I am also using codeblocks IDE
#include <iostream>
using namespace std;
int main()
{
// Addition and Subtraction Calculator
int a_number, number1, number2, sum, number3, number4, subsum, again;
// subsum = subtracted sum
// number1 and number2 are variables that hold the users input for addition
// number3 and number4 are variables that hold the users input for subtraction
do
{
cout << "Addition & Subtraction Calculator" << endl;
cout << "-------------------------------------------" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;
while (a_number < 1 || a_number > 2)
{
cout << "Please enter either 1 or 2" << endl;
cin >> a_number;
}
switch (a_number)
{
case 1:
cout << "Please enter a number" << endl;
cin >> number1;
cout << "Please enter another number" << endl;
cin >> number2;
sum = (number1 + number2);
cout << "The sum is " << sum << endl;
break;
case 2:
cout << "Please enter a number" << endl;
cin >> number3;
cout << "Please enter another number" << endl;
cin >> number4;
subsum = (number3 - number4);
cout << "The answer to the subtraction problem is: " << subsum << endl;
break;
}
cout << "Do you want to try again? [y/n]" << endl;
cin >> again;
}
while (again == 'y' || again == 'n');
return 0;
}
OK. So the OP is using an int where they should have used a char. That covers the immediate problem. int again should be char again.
But there is an important point the other answers have missed.
int again;
cin >> again;
The user input will be converted into an integer as required by again. Inputting y or n fails to convert to an integer as neither y nor n are numbers and cannot be converted. again remains unchanged, keeping whatever junk value happened to be sitting at that spot in memory and might actually be a y or an n, but more importantly cin is now in an error state that needs to be cleared before continuing.
cin would have notified the OP of this if it had been tested. So let's test it.
int again;
if (cin >> again)
{
// got good input. Do something with it.
}
else
{
// got bad input.
cin.clear();
// that bad input is still in the buffer and needs to be removed
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// the above line will wipe out everything to the end of the stream or
// end of line, whichever comes first.
}
Why this is important: Because the OP is doing a lot of numeric input with cin and none of it is checked for validity. For example:
cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;
The program is broken completely and cannot exit without a kill signal if the user types in anything but a number.
Always check the error state and return codes. They are there to help. Always validate user input before using it. Users are evil and will try to break your program. Don't let them.
use char again; instead of int again;
in your code again is int and when in (again == 'y' || again == 'n')you compare again (an int) with a char, that does not make sense
You need to change the again variable to a char datatype because you need to store text. Something like this:
char again;
You also need to change the while statement to:
while(again != "n");
Or
while(again == "y");

After receiving NaN input C++ program asks for input again then quits

I’m a beginning C++ programmer and this is only my second program... It’s a simple money converter between dollars and Euros. The problem I have is that if I put in a NaN value, it’ll say so and ask again but quit. Does anyone know how to make it wait until the user types something else? Also at the second cin >> user_dollar I’m getting an error that says “Reference to overloaded function could not be resolved; did you mean to call it?” Sorry that this is so long and thanks~
Here is my code. I’m using Xcode on my MacBook Pro.
#include <iostream>
using namespace std;
int main() {
string choice;
int user_dollar;
int user_euro;
cout << "Dollars to Euros (type ‘Dollars’) or Euros to dollars (type ‘Euros’)? ";
cin >> choice;
if (choice == "Dollars" || choice == "dollars") {
cout << "Enter dollar amount: ";
cin >> user_dollar;
if (isdigit(user_dollar) != true){
cout << "That’s not a number... " << endl;
cout << "Enter dollar amount: " << endl;
*cin >> user_dollar;*
}
else {
cout << "That is " << user_dollar / 1.13 << " Euros." << endl;
}
}
else if (choice == "Euros" || choice == "euros") {
cout << "Enter Euro amount: ";
cin >> user_euro;
cout << "That is " << user_euro * 0.89 << " dollars." << endl;
}
}
You need to flush the cin buffer before second use of cin. Something like
cin.clear();
cin.ignore(INT_MAX,'\n');
cin >> user_dollar;
Take a look at this thread for more details on flushing the buffer.
Since the type of the user_dollar variable is an int, it can only hold an integer. If someone types something besides a number (like "hi"), it cannot be stored in user_dollar.
When you call cin >> user_dollar, and the user enters a non-number, it fails and does not change user_dollar. Since nothing else has set user_dollar at that point, it could be anything--semi-random garbage. You are currently checking that garbage with isdigit(). And isdigit() is not for checking integers read directly using cin.
You can check if it failed to read a number by calling fail(), use clear() to reset whether there was an error, and ignore() to flush the buffer as Igor shows.
As philipxy said, you can use a while loop to keep asking until a number was successfully read.

cin in while loop doesn't work properly (C++)

This program should check if entered number is integer. It works fine with strings but not with doubles.
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
test is int. istream >> operator is just dynamic casting to int and, then, you're losing decimal part.
Yo can just define test as float and cast it to int when needed.
Edit: Answering you last edit (I didn't refresh so I missed this part), what is happening is that, without the gotoyou're looping twice:
You enter 1.5
test is 1 and you don't enter if, so cin is not cleaned up.
loops again and cin immediately returns.
test is 0 so enters if statement and complains.
Hope this helps
Try this:
int test;
cout << "Enter the number:" << endl;
while ( true )
{
cin >> test;
if (!(test < 0 || !cin))
break;
}
cout << "Your chosen number is: " << test << endl;
Is that what you want?