Check if the user input has entered a repeated number - c++

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

Related

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

Confusing C++ Assignment

I'm a freshman college CS student, and I can't seem to figure this problem out. It basically wants me to ask the user for the amount of students in a particular class, and then continuously loop asking for the students names. After all that is done, I have to find out which name that was entered will be first, alphabetically, and which name will be last, alphabetically.
My code so far does everything up until I have to sort through the names, as well as displaying the names incorrectly. It only displays the latest name entered, not both names at once.
#include <iostream>
#include <string>
using namespace std;
int main () {
int studentCount;
string studentName;
cout << "Hello fellow educator!" << endl;
cout << "I will be helping you with your line-up for today." << endl;
cout << "Please enter the number of students in your class: ";
cin >> studentCount;
cout << endl;
cout << endl;
if (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25." << endl;
cout << endl;
}
for (int count = 1; count <= studentCount; count++) {
cout << "Please enter a student's name: ";
cin >> studentName;
}
cout << "the names are " << studentName; // Just testing the string
return 0;
}
As you collect names, Store the names in a data structure.If you keep adding all names to a single string, then, it can be stored as one concatenated string but we want different names(strings).
So, Lets take vector as our datastructure.
int main () {
int studentCount;
string studentName;
vector<string> attendanceBook;
for (int count = 1; count <= studentCount; count++) {
cout << "Please enter a student's name: ";
studentName.clear();
cin >> studentName;
attendanceBook.push_back(studentName);
}
std::sort(attendanceBook.begin(),attendanceBook.end());
cout<<"First: "<<name.front<<endl<<"Last: "<<name.back();
So this is the completed code, after hours of work, and it runs and does everything properly. It's simple, I know, but to a college freshman only having been exposed to the surface of Java, this is complicated to me. :) I knew there was a way of doing this without vectors or arrays.. Thanks to everyone who tried their best to help me. I'll be sure to come back in the future.
#include <iostream>
#include <string>
using namespace std;
int main () {
int studentCount;
string studentNames;
string first;
string last;
cout << "Hello fellow educator!" << endl;
cout << "I will be helping you with your line-up for today." << endl;
cout << "Please enter the number of students in your class: ";
cin >> studentCount;
cout << endl;
cout << endl;
while (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25: ";
cin >> studentCount;
}
for (int count = 0; count < studentCount; count++) {
cout << "Please enter the name for student number " << count + 1 << ":";
cin >> studentNames;
if (count == 1) {
first = studentNames;
last = studentNames;
}
else {
if (studentNames < first) {
first = studentNames;
}
else if (studentNames > last) {
last = studentNames;
}
}
}
cout << "The first student in line is " << first << "." << endl;
cout << "The last student in line is " << last << "." << endl;
return 0;
}
First, you need to make an array of string instead of a single string to avoid overwriting.
After that, sort them lexicographically and print them.
EDIT:
Have a look at the code given below:
#include <iostream>
#include <string>
#include <algorithm> /* Used to sort the string lexicographically */
#define LIMIT 50 /* I'm considering that you are not providing more than 50
names at once to a program*/
using namespace std;
int main () {
int studentCount; /* Count number of the students */
string studentName[LIMIT]; /* Array of string */
cin >> studentCount; /* Input number of student */
/* Keep on asking until the correct value of studentCount is not provided */
while (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25." << endl;
cin >> studentCount;
}
cout <<"Please enter a student's name: ";
for (int count = 0; count < studentCount; count++) {
cin >> studentName[count]; /* I started the count value from 0 to n-1
because the index of an array starts from 0 */
}
/* Now, time to sort the array of string lexicographically */
sort(studentName, studentName+studentCount);
/* Print the names of the student */
cout << "Names of the students : " << endl;
for(int i=0; i< studentCount; i++) {
cout << studentName[i] << endl;
}
return 0;
}
This code will keep on asking until correct value of studentCount is not received. You can even change the upper limit of the program by changing the value of LIMIT from 50 to something else you may need.

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

Comparing a user specified amount of numbers inside of a user definded function in c++

first time poster here.
Please keep in mind I'm still very new to c++ and coding in general.
I'm trying to rewrite a program that asks the user how many numbers they want to compare, then they enter the values of each number. I have achieved this via for and if statements, but i am now asked to do this with user defined functions instead. The problem I have so far is that the first number I enter is the one saved, but it does prompt for additional numbers and the for loop inside of the function works properly. Some suggestions to what I'm not doing correctly would be greatly appreciated. I have all the variables declared that are needed, so i only put the prototype in to save on space.
int main()
{
int DisplayGreatest(int,int);
do {
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cin >> currentAinput;
DisplayGreatest (Aselection,currentAinput);
cout << "The largest number is "<< currentAinput << endl;
}
}
}
The function:
int DisplayGreatest(int Aselection, int currentAinput)
{
int i;
int keepAinput=0;
for(i=1;i<Aselection;i++)
{
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput=currentAinput;
}
}
return currentAinput;
}
You have several errors in your code:
First you are not using the returned value from the function DisplayGreatest
You are never comparing the first value you enter with the others (you do two cin in a row without before the first comparison)
Declaring the function DisplayGreatest in the wrong scope (should be in the global scope, or place the whole function before main)
You have no end condition to your do-loop in main. (missing while statement, maybe you have that in your own version)
You returned the last value entered in the DisplayGreatest function, not the largest one.
Here is a functional version:
#include <iostream>
using namespace std;
int DisplayGreatest(int Aselection)
{
int keepAinput = 0;
int currentAinput;
do {
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput = currentAinput;
}
} while(--Aselection > 0);
return keepAinput;
}
int main()
{
char Selection;
do {
int Aselection;
int currentAinput;
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cout << "The largest number is "<< DisplayGreatest (Aselection) << endl;
}
} while(Selection != 'C' && Selection != 'c');
}
int DisplayGreatest(int,int) should probably be declared in the global namespace, ie:
int DisplayGreatest(int, int);
int main()
{
}
int DisplayGreatest (int Aselection, int currentAinput)
{
}
Also, you can take in input in a loop but it is somewhat more natural take in a whole vector worth of ints and then find the highest/lowest using the same idea (loop through each one and save the current highest/lowest).
EDIT: Oh, I see what your issue is now. You need to return keepAinput at the end of your function and assign it to currentAinput or another variable and print whichever you assign it to. Or just print the result directly, IE:
cout << "Highest number is " << DisplayGreatest(Aselection, currentAinput) << endl;

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