Reputation: 3
My code: http://pastebin.com/qjFd6KXb
I have an assignment for class that requires me to create a program that will output a simple multiplication question that the user has to answer in three tries or less. One of the requirements is that the program checks that the users guess is a valid number. My professor wants us to use this method in our code:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char c;
bool valid = false;
int i;
while (!valid)
{
cout << "Enter an int " << endl;
cin >> i;
valid = true;
if (cin.peek() != '\n' || cin.fail()) // checks if the input data was correct or not
{
valid = false;
cin.clear(); // clears the error flags
cin.ignore(100, '\n'); // ignores up to 100 characters in the cin stream
}
}
}
My problem comes in at about line 57 of my code. Without the extra while loop and if statement to check for correctness, it runs fine. However no matter what I try, when I implement that part it either becomes an infinite loop, or impossible to win. If someone could let me know what is wrong with this I'd greatly appreciate it, as I can't for the life of me figure this one out.
Upvotes: 0
Views: 536
Reputation: 2056
Your check can be achieved like this:
std::cin >> i;
while( std::cin.fail() ) {
std::cout << "Bad Input\nEnter an Integer, foo: ";
std::cin.clear();
std::cin.ignore('256','\n');
std::cin >> i;
}
I'm not sure why you are peaking and looking for the end of line
Upvotes: 0
Reputation: 25397
Just took a short look at your code.. I think
tries = tries + 1; // Adds one to the tries counter
is in the wrong scope
while ((choice != 1) || (choice != 1) || (choice != 1));
cout << "Try to solve the problem!\n"; // Provides instruction to the user.
while ((result != guess) && (tries < maxtries))
{
}
tries = tries + 1; // Adds one to the tries counter
}
should be
while (choice != 1);
cout << "Try to solve the problem!\n"; // Provides instruction to the user.
while ((result != guess) && (tries < maxtries))
{
tries = tries + 1; // Adds one to the tries counter
}
}
Upvotes: 1