I would like to validate if the user input is Float or not, the program checks if the input was float and prints "Number is fine" else it prints "Number is not fine" and it continue the loop without taking the failed attempt in consideration of the loop, in other way it gives him another try to enter a float number instead.
The problem is that the program goes on infinity loop once the user enter a "Character". what i actually want it to do is just printing "Number isn't fine" then continue.
Can anybody tell me why does this happen, also please consider not to use any additional libraries.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x;
float num;
cout << "Please enter the amount of numbers you wish to enter" << endl;
cin >> x;
cout << "Please enter the numbers" << endl;
for(int i=0; i < x;) {
if(!(cin >> num)) {
cout << "Number isn't fine" << endl;
continue;
}
cout << "Number is fine" << endl;
++i;
}
system("pause");
}
#Steve your solution worked by using both cin.clear() and cin.ignore
#AndyG Thanks for your help but unfortunately im limited to the simplest way.
Here is the final code if somebody wanted to know how it looks in the future.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x;
float num;
cout << "Please enter the size of numbers" << endl;
cin >> x;
cout << "Please enter the numbers" << endl;
for(int i=0; i < x;) {
if(!(cin >> num)) {
cin.clear();
cin.ignore();
cout << "not a float number" << endl;
continue;
}
cout << "Number is fine" << endl;
++i;
}
system("pause");
}
If cin >> num fails to read a number then the stream is put into the failed state (that is, the failbit is set), and it doesn't read past the character that caused it to fail. You never do anything to clear() the fail state or to ignore() the bad data, so you loop forever.
Related
This question already has answers here:
Good input validation loop using cin - C++
(4 answers)
Closed 1 year ago.
So when i enter a char or string, it asks the question again but infinitely... but i want it to ask once every time wrong, then again if wrong. Get it... ? :( right now the loop is infinite.
#include <iostream>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
cin >> money;
if (money) {
cout << "You have: " << money << "$" << endl;
} else {
cout << "You have to enter numbers, try again." << endl;
}
} while (!money);
return 0;
}
You are not validating and clearing the cin stream's error state. Try this instead:
#include <iostream>
#include <limits>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
if (cin >> money) {
// a valid float value was entered
// TODO: validate the value further, if needed...
break;
}
else {
// an invalid float was entered
cout << "You have to enter numbers, try again." << endl;
// clear the error flag and discard the bad input...
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
while (true);
cout << "You have: " << money << "$" << endl;
return 0;
}
I'm starting now with C++, so I imagine this is gonna be a very easy-newbie question.
Well, why the "cin >> x" line inside while doesn't stop the loop to get the user input (if the user inputs a character, in place of a number)?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cout << "Please, it must be a number!\n";
cin >> x;
}
cout << "Thanks!.";
cin.ignore();
cin.ignore();
}
I'm barely two days studiying C++, so I'm completely blind about what "cin" really is. I tried with "cin.sync()" and "cin.clear()", but still no luck.
And I know it is impossible to do something like "cin=true", or "cout << cin".
Well, your program should be corrected slightly
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cin.clear();
cin.ignore(10000, '\n');
cout << "Please, it must be a number!" << endl;
cin >> x;
}
cout << "Thanks!.";
}
This way it works as expected. More info about it here. In general, you need to clear all the errorneous stuff from cin.
if user input a character than it will take the ascii value of character so it will not stop.
To stop the loop enter 0.
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");
I am kinda new to C++, and I have encountered a problem in building a simple c++ addition calculator. Here is the code:
#include <iostream>
#include <string>
#include <climits>
using namespace std;
int main()
{
int number;
int total = 0;
int x = 0;
int z = 5;
cout << "Please enter the number you want to add" << endl;
while(x < 5 && z != 0){
cin >> number;
if (!cin){
cout << "Enter a valid number. " << "You have" << z << "tries left before this program terminate." << endl;
cin.clear();
z--;
}
else{
total = total + number;
x++;
}
}
cout << "The total number is " << total << endl;
return 0;
}
When I run the application and then I input a non-integer, it shows "you have _ tries left" altogether. How do I make the application so that it will give the user a chance to input a something?
One simple solution would be to add
std::string junk;
cin >> junk;
just after cin.clear(). This will extract the junk and put it in junk, and just skip over it.
You could use ignore(). I don't know how many junk characters you'll have, but you could try something like
cout << "Enter a valid number. " << "You have" << z << "tries left before this program terminate." << endl;
while (!cin.eof())
cin.ignore();
cin.clear();
In the below code, I'm running into an error when I try to get the user to input their name. My program just skips it over and goes right over to making the function calls without allowing the user to enter their name. Despite the error, my program is compiling. I'm not sure what's going wrong as I wrote that part based off other examples I found on here. Any suggestions?
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
char showMenu();
void getLottoPicks(int[]);
void genWinNums(int[]);
bool noDuplicates(int[]);
const int SIZE = 7;
int main()
{
int userTicket[SIZE] = {0};
int winningNums[SIZE] = {0};
char choice;
string name;
srand(time(NULL));
do
{
choice = showMenu();
if (choice == '1')
{
cout << "Please enter your name: " << endl;
getline(cin, name);
getLottoPicks(userTicket);
genWinNums(winningNums);
for (int i = 0; i < SIZE; i++)
cout << winningNums[i];
}
} while (choice != 'Q' && choice != 'q');
system("PAUSE");
return 0;
}
Added the code for showMenu:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
return choice;
}
And getLottoPicks (this part is very wrong and I'm still working on it):
void getLottoPicks(int numbers[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << "Selection #" << i + 1 << endl;
cin >> numbers[i];
if (numbers[i] < 1 || numbers[i] > 40)
{
cout << "Please choose a number between 1 and 40: " << endl;
cin >> numbers[i];
}
if (noDuplicates(numbers) == false)
{
do
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> numbers[i];
noDuplicates(numbers);
} while (noDuplicates(numbers) == false);
}
}
}
After doing cin >> choice; inside char showMenu(), if a user inputs 1[ENTER], the char consumes 1 character from cin, and the newline stays inside the stream. Then, when the program gets to getline(cin, name);, it notices that there's still something inside cin, and reads it. It's a newline character, so getline gets it and returns. That's why the program is behaving the way it is.
In order to fix it - add cin.ignore(); inside char showMenu(), right after you read the input. cin.ignore() ignores the next character - in our case, the newline char.
And a word of advice - try not to mix getline with operator >>. They work in a slightly different way, and can get you into trouble! Or, at least remember to always ignore() after you get anything from std::cin. It may save you a lot of work.
This fixes the code:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
cin.ignore();
return choice;
}
from looking at code showMenu function has problem. and it's not returning asccii equivalent of '1' that is: 31 integer. try printing value returned by showmenu. you will get that
UPDATE:
It is because cin in delimited by ' '(whitespace) and getline by '\n' character, so when enter name and press enter cin in showmenu will consume whole string except '\n' from istream and that is read by getline. to see this when it ask for choice enter string like 1 myname (1 whitespace myname)and press ENTER will display name. now cin will read 1 in choice and myname in name by getline.