I have written a program that asks the user to input integers 10-100, inclusive, and load them into a vector. It should validate the number, check for duplicates
and then add it to the vector if the proper conditions are met.
The function to check for duplicates is working, but my issue is with the validation function. However, when testing with invalid input the initial wrong number is stored in the vector and the following number that is input and tested is not stored. i.e. I enter 3, get invalid input message, enter 10 and keep going. Upon finishing the vector shows the 3 and not the 10.
Here is my code:
#include<iostream>
#include <vector>
using namespace std;
class Vector
{
private:
int num;
vector<int> num;
public:
int validateValues(int);
bool duplicateValues(int, vector<int>&);
void showValues(vector<int>);
else
{
do
{
cout << "Invalid number. Enter a number between 10 and 100 inclusive." << endl;
cin.sync();
cin.clear();
cin >> n;
number = n;
} while (n =! cin || n < 10 || n > 100);
}
return number;
};
bool Vector::duplicateValues(int n, vector<int>&num)
{
bool value = false;
for (int k = 0; k < num.size(); k++)
if (n == num[k])
value = true;
return value;
};
void Vector::showValues(vector<int> vect)
{
cout << "The numbers you entered are: \n";
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << ", ";
cout << endl;
};
int main()
{
Vector v1;
vector<int> number;
int num;
welcome();
cout << "Enter a number, or '999' to finish: " << endl;
do
{
cin >> num;
v1.validateValues(num);
if (num != 999)
if (v1.duplicateValues(num, number))
cout << "The number has already been entered.\n";
else
{
number.push_back(num);
}
} while (num != 999);
v1.showValues(number);
cout << endl << endl;
cout << "Number of values in vector: " << number.size() << endl;
return 0;
}
/*****************Welcome*****************/
void welcome()
{
cout << "Please enter numbers between 10 and 100, inclusive.\n Duplicates will not be saved. \n Enter '999' when you are done." << endl << endl;
}
validateValues does more than just validate a value (why is it plural?). It also asks for a replacement value if it determines the value is invalid. This replacement value is returned by the function, but you don't do anything to catch the value returned so it is immediately lost, and the code goes happily on with its invalid value.