C++ Infinity While Loop with condition - c++

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

Related

Check if the user input has entered a repeated number

So i am still a beginner at this and still practising. Basically i need to make a program that continues to asks the user to enter any number other than 5 until the user enters the number 5.
I have that done but i could't figure out how to check if the user entered a repeating number.For example:
1
2
3
3 - The program should end
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
cout << setw(15) << setfill('*') << "*" << endl;
cout << "Number 5" << endl;
cout << setw(15) << setfill('*') << "*" << endl;
int num;
cout << "Enter a number: ";
cin >> num;
if (num == 5) {
cout << "\nWhy did you enter 5? :) " << endl;
_getch();
exit(0);
}
for (int i = 1; i < 10;i++) {
cin >> num;
if (num == 5) {
cout << "\nWhy did you enter 5? :) " << endl;
_getch();
exit(0);
}
}
cout << "Wow, you're more patient then I am, you win." << endl;
_getch();
}
The previous answer does not meet the requirement in the linked article, which the querist himself seemed to not grasp:
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)
This variant complies:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
{
cout <<"Please enter any number other than " <<i <<": ";
int num;
cin >>num;
if (num == i)
return cout <<"Hey! you weren't supposed to enter " <<i <<"!\n", 0;
}
cout <<"Wow, you're more patient then I am, you win.\n";
}
You could add all inputted numbers to a vector, and whenever you get a new number, check if it's already in the vector. Include these headers:
#include <vector>
#include <algorithm> // for std::find
Make the vector like this
std::vector<int> pastEntries;
Do the check like this:
if (std::find(pastEntries.begin(), pastEntries.end(), num) != pastEntries.end()) {
std::cout << "\nWhy did you enter " << num << "? :) " << endl;
...
And when the number was not found, add it to the vector like this (you can put this after the if block):
pastEntries.push_back(num);
Alternatively, you can use std::set:
std::set<int> pastEntries;
Insert into the set like this:
pastEntries.insert(num);
And find the number in the set like this:
if (pastEntries.find(num) != pastEntries.end()) {
Or insert the number while finding out whether it has already been inserted like this:
if (!pastEntries.insert(num).second) {

How do I restrict the user to number only inputs?

Ok, so basically I am having to make a basic program for a club at my school. I am trying to make it to where when the user inputs something that is not a number, it has an error message and loops back around to ask for the number again. This is not it exactly, but something I threw together real quick as an example.
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int a;
int b;
do{
cout << "Welcome to the equalizer. Please enter a number." << endl;
cin >> a;
cout << endl << "Ok, now I need another number." << endl;
cin >> b; //if a number is not entered, I need an error message and a loop back to the request for the number.
if(a>b){
cout << a << " is greater than " << b << endl;
}
if(b>a){
cout << b << " is greater than " << a << endl;
}
if(b=a){
cout << a << " is equal to " << b << endl;
}
cout << "restart? Enter Y if yes, or enter anything else to close." << endl;
cin >> c;
}while(c=="y" || c=="Y");
return 0;
Well, if I got it right, you can use something like "isdigit('char')". Do not forget to include "ctype.h".
In your code it will be something like:
if (!isdigit(c))
continue;
If the number may be a string like "1232321" then you may need to iterate through that string checking each char and exit if it is not...
bool error = false;
for (int i = 0; i < c.length(); i ++)
{
if (!isdigit(c[i]))
{
error = true;
break;
}
}
Hope, this helps.
P.S. Of course, "a" and "b" in your example should be of type string or char...

how do you do a integer validation in C++?

ok, I have been looking for days now but I cant find anything that will work.
I have a program and I want to make sure that the user enters a integer and not a double.
this program works fine but I need to validate the numOne and numTwo to make sure they are integers and not doubles, (5.5)
int main()
{ //This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl;
cout << "Please enter the beginning number." << endl;
cin >> numOne;
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a integer(if not the program will close)
if (!(cin >> numOne))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a number(if not the program will close)
if (!(cin >> numTwo))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (numOne - numTwo) + 1;
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (numOne - numTwo) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer)
{
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
Use std:n:ci.fail() to see if it failed.
int numOne;
cin >> numOne;
if(cin.fail())
cout << "Not a number...")
Maybe even a nice template function.
template<typename T>
T inline input(const std::string &errmsg = "") {
T var;
std::cin >> var;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << errmsg;
std::cin >> var;
}
return var;
}
Or not:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ctime>
#define DIFF(n1, n2) (n1 > n2 ? n1 - n2 : n2 - n1)
using namespace std;
int input(const string &firstmsg = "", const string &errmsg = "") {
int var;
std::cout << firstmsg;
std::cin >> var;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '\n');
cout << errmsg;
cin >> var;
}
return var;
}
int main(){
//This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl << endl;
numOne = input("Please enter the beginning number: ", "Invalid. Enter again: ");
//this asks the user for the second number
numTwo = input("Please enter the ending number: ", "Invalid. Enter again: ");
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (DIFF(numOne, numTwo)) + 1; // ensures it will always be positive
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (DIFF(numOne, numTwo)) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer){
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
why not, get the number into a double and then see if that double is an int. ie
double d;
cin>>d;
if (ceil(d) != d)
cout >> " not an integer";

C++ while loops on my program

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
double Donor = 0.0;
int totalRaised = 0;
cout << "Enter amount donated by first donor [or -1 to stop]:" << endl;
cin >> Donor;
while (Donor != -1)
{
cout << "Enter amount donated by next donor [or -1 to stop]:" << endl;
cin >> Donor;
totalRaised = totalRaised + Donor;
}
cout << "Total amount of money raised: " << totalRaised << endl;
system("pause");
return 0;
}
This is my code and my goal is to have the user put the input in and when done enter in -1 and display the total amount enter from the user but my problem when I run this code I do not get the correct value. Could someone point me in the right direction and explain how to make the program run correctly. Thank you.
while (Donor != -1)
{
cout << "Enter amount donated by next donor [or -1 to stop]:" << endl;
totalRaised = totalRaised + Donor;
cin >> Donor;
}
see if it works.
you have to add the first input which was before the while loop and then go for the next input

C++ Check if input is float using only #iostream

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.