How do I restrict the user to number only inputs? - c++

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...

Related

C++ random srand code-if else does not give correct result

I am not receiving correct response to my code. It should give 'Excellent' when I type in correct number; however, it always outputs 'Incorrect' - Please suggest.
#include <iostream>
#include <ctime>
using namespace std;
int guess()
{
int x = 0;
x = 1 + rand() % 1000;
return x;
}
int main()
{
int input = 0;
srand( time( 0 ) );
cout << guess() << endl;
cout << "I have a number between 1 and 1000. " << endl;
cout << "Can you guess my number? " << endl;
cout << "Please type your first guess. " << endl;
cin >> input;
if (guess() == input)
cout << "Excellent! You guessed the number! " << endl;
else
cout << "Incorrect! " << endl;
system ("pause");
return 0;
}
You are calling twice the function guess(), so it will give you probably different values at each run. You must store the value and then compare it with the original one.

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) {

c++ segmentation fault (core dumped) with modulus

I am working on a program that allows the user to practice division. My code is below:
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
return main();
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
return main();
}
return 0;
}
Basically, what it is supposed to do is first choose two random numbers. Then, it is supposed to check to see if the second number (div2) is greater than the first (div1), and if they are, it will switch them. Then, it will use the modulus (div1%div2) to make sure that the two numbers can be divided by each other without a remainder. If they cannot be divided without a remainder, it will restart the program (return main();). However, whenever I run it, I get the segmentation fault: core dumped, either when I start it or after running it a few times. Any ideas on how to fix this?
Thanks!!
Here's an example of what I've said in the comments. Obviously, you can refactor this so that it works more gracefully (as of now it'll give you floating point exceptions sometimes), but it gives you an idea on how to do this without calling main again.
NOTE: You do not need to make a constant for NEWLINE. There is already a built-in constant in std. In fact, you're already using that constant (endl). So you can just do cout << endl instead of cout << NEWLINE.
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
while(true) {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
}
}
return 0;
}
This code can get into "divide by 0" error. This is why you would be getting error.
The line "if (div1%div2!=0) {" seems erroneous.
In this line if div2 == 0, then your code will crash.

Prompt user for positive number, and continues to prompt the user until they enter a positive number c++

//review3
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
while (number < 0)
{
cout << "Enter a positive number" << endl;
}
if (number > 0)
{
cout << "Awesome job!" << endl;
}
return 0;
}
This is my code so far. I started with an else if but if the user entered a negative number the program would simply close. I changed this to a while loop and got stuck in an infinite loop. Before I had an if and else if statement. I need to continue to prompt the user until they enter a positive number in c++.
Your while() loop doesn't continue to prompt for input, that's why you're getting an infinite loop - because number never changes!
You can put the input operation into the while() loop like this:
while (cin >> number && number < 0)
{
cout << "Enter a positive number: " << endl;
}
if (cin)
{
cout << "Awesome job" << endl;
}
Thus, during each iteration of the loop the user will be prompted for input.
We check the state of cin afterwards to make sure that the above loop didn't stop because of invalid input (or no input at all).
#include <iostream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
if (number < 0) {
cout << "Enter a positive number" << endl;
}
else {
cout << "Awesome job!" << endl;
}
return 0;
}
You can check if you get number or string here
sure in this case you should get input to string variable. If you want to convert it to integer you can use std::stoi
#include <iostream>
#include <string>
#include <cstring>
int main()
{
while(true)
{
std::cout << "Pleaase enter a positive number." << std::endl;
std::string buf;
int x = -255;
std::cin >> buf;
x = std::atoi(buf.c_str());
if(x > 0)
{
break;
}
}
std::cout << "Awesome Job!" << std::endl;
}
You can also do this snippet . Use #include <ctype.h> or <cctype>
while(1){
cin>>number;
if(number<0 || isalpha(number)) return 0;
cout<<"Awesome Job";
}

C++ Infinity While Loop with condition

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