duplicate name checking function for an array - c++

I am still a beginner in C++, so I'm sorry if the question is simple.
I am trying to build a program that asks you to input names and register them to an array. Then, I need to call a function to check if there are any duplicate names. If there are any, it asks the user to input another name.
The problem I'm having is that the function is called whether or not there are duplicates, and always replaces the first name that was entered.
int checking(string stringArray[5]) {
int i, z ;
for (i = 0; i < 5; i++) {
for (z = 0; z < 5; z++) {
if (z != i) { // Makes sure don't check number against itself
if (stringArray[z] == stringArray[i]) {
return i;
}
else {
return 0;
int main(){
for (i = 0; i < 5; i++) {
cin >> stringArray[i];
}
j = checking(stringArray);
if (j == 0) {
cout << "Please re-enter name " << ". Duplicate names are not allowed"
<<'\n';
cin >> stringArray[j];
}

Some observations (ignoring the syntax errors, I assume these are not present in your actual code):
z doesn't need to start at 0 every time, it can start at i + 1 because you dont need to check pairs you have already checked (makes it simpler and runs faster)
you don't want to return in your loop, it will prevent you from checking past the first repeated name. Instead move your reenter statement into the loop.
generally you dont want to use literals (5) in a loop, instead use a variable to store the length of the array and compare to that (this is just a general programming rule, it won't change how the code runs)
Your final checking() function should look closer to:
void checking(string stringArray[5]) {
int i, z ;
// consider replacing 5 with a variable
for (i = 0; i < 5; i++) {
for (z = i+1; z < 5; z++) {
if (stringArray[z] == stringArray[i]) {
cout << "Please re-enter name " <<
". Duplicate names are not allowed" <<'\n';
cin >> stringArray[z];
/* restart the loop user may have entered a */
/* second duplicate from previous entries */
i = 0;
z=i+1;
}
}
}
}

Related

Array will not fill backwards in C++

I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];
What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.

Working with vectors C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Complicated question, probably simple answer. So the program I need to make cannot include any library other than String, iostream, and vector. I need to create a program that has 3 functions. One that creates an integer vector, one that reverses a vector, and one that prints a vector. In order to take in values I need to use getline to intake a string, if the string states quit, we stop putting new values into it. Other wise we need to test if its an integer(positive or negative) and add it to the vector. My code is starting to get complicated so I really need some help. Below is what i have so far. I'm also using Visual Studio, if that matters. Thanks for any help in advance! The question I have is when I run the program, it will only output the first digit. I don't know why and would like to know what I'm doing wrong.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> CreateVector()
{
string tempvariable;
bool quit = false;
vector<int> userinput;
cout << "Please enter in an integer, type 'quit' to exit " << endl;
while (!quit)
{
getline(cin, tempvariable);
if (tempvariable == "quit")
quit = true;
else
{
bool isaninteger = true;
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
continue;
else
{
cout << "You entered in an incorrect option, please enter in a correct option" << endl;
cin.clear();
cin.ignore();
isaninteger = false;
break;
}
}
if (isaninteger)
userinput.push_back(stoi(tempvariable));
cout << "Please enter in an integer, type 'quit' to exit " << endl;
}
}
return userinput;
}
void printVector(vector<int> userinput)
{
int amountofspots = userinput.size();
cout << "Your Vector is ";
for (int i = 0; i < amountofspots; i++)
{
if (i = (amountofspots - 1))
cout << userinput.at(i) << endl;
else
cout << userinput.at(i) << " , ";
}
}
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
for (int i = 0; i < amountofspots; i++)
userinput.pop_back();
for (int i = 0; i < amountofspots; i++)
userinput.push_back(tempvector.at(i));
}
int main()
{
vector<int> CreatedVector = CreateVector();
printVector(CreatedVector);
reverseVector(CreatedVector);
printVector(CreatedVector);
system("pause");
return 0;
}
Change if (i = (amountofspots - 1)) to if (i == (amountofspots - 1)) in the loop in printVector().
Change tempvariable[i] = "-" to tempvariable[i] == '-' in CreateVector().
= is the assignment operator, == is the comparison operator. Also, single characters are surrounded by single quotes, not double quotes.
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
should probably be
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 1; i < amountofspots+1; i++) // Index error
tempvector.push_back(userinput.at(amountofspots - i));
The following:
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
Must become:
for(int i = 0; i < tempvariable.size(); i++)
{
if (tempvariable[i] == '-' || isdigit(tempvariable[i]))
Explanation:
String indices start from 0 and end at size() - 1.
[i] returns a single char. "-" is not a single char but an entire string literal. You cannot directly compare a single char with an entire string. -, however, is a single char, so that comparison will work.
= is not comparison but assignment. == is used for comparison. As your compiler should have warned you!
Note that there are further problems with your code:
if (i = (amountofspots - 1))
You are again mixing assignment and comparison. Make that ==. And pay attention to compiler warnings!
And finally, isdigit is not exactly a great function. In order to really use it correctly, you'd first have to cast the operand to int and at the same time make sure it is not an invalid value, as documented here.
Why don't you just catch the exception thrown by stoi if the specified string cannot be parsed?

Can't figure out why this output formatting loop is going infinite

My program is supposed to take in a number from user input, determine whether or not it is prime, and then if it is not, output the factors of the entered number, 5 to a line. The 5 to the line part is where everything goes haywire, the loop i wrote should work fine as far as i can tell, however no matter how much i change it around, it does one of two things, 1) goes infinite with either new lines or the first factor, or 2) outputs a line with 5 of each factor. Here's the code:
else
{
cout << "\nNumber is not prime, it's factors are:\n";
for (int x = 2; x < num; x++)
{
factor=num%x;
if (factor==0)
{
int t=0;
cout << x << "\t";
t++;
for (int t; t <= 5; t++) // THE TROUBLE LOOP
{
if(t>=5)
{
t=0;
cout << endl;
}
}
}
}
}
Replace the declaration of t in the loop since you've declared t prior to the loop:
for(; t <= 5; t++)
With int t in the loop declaration you are overriding t as an uninitialized variable that will have a garbage value.
Outside of this problem your loop is infinite since you will be resetting t to 0 whenever it equals 5.
In the for loop change the
int t
to
t=0
it is the
for(int t,t<=5,t++)
the int t part in particular that is causing the issue.
#GGW
Or this:
int t = 0;
//some code
for(t; t <= 5; t++)
//more code

Searching by price in a 2D array?

I have a program that builds a 2D array of a theater. The user can select a seat by position and the monetary amount is changed to a 0 to indicate that the seat is taken. The other method of choosing a seat selects by price. So the user enters a price, a for loop iterates through the array and finds the first instance of that price and replaces it with a 0, then stops. Or at least that's what I tried to do. In practice, it replaced all of those values with 0. I tried using a while loop to close it out once the condition is met, but that didn't work. Here's my (relevant) code.
while (flag == true)
{
cout << "\n";
cout << "You may select tickets by seat or by price. Enter 1 to select by price, or 2 to select a seat. Enter 3 if you'd like to quit." << endl;
cin >> userSelection;
if (userSelection == 1)
{
cout << "What price would you like to search for? " << endl;
cin >> priceSelection;
while (searchFlag == true)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
if (Theater [i][j] == priceSelection)
{
Theater [i][j] = 0;
searchFlag = false;
}
}
}
for (int i = 0; i < 9; i++) // This for loop is going to output our array so the user can see pricing.
{
for (int j = 0; j < 10; j++)
{
cout << Theater [i][j] << " ";
}
cout << "\n";
}
}
}
I'm not sure what really needs to change so that it'll stop after the first price is found and changed. Also, I don't mind to copy/paste the rest of my code if that's necessary.
Just some advice for the future,
Don't hardcode your loop termination conditions i.e. (i < 9). Have a current length of the array, or number of seats. That way you ever add more, this will still work.
Also even though you set search flag to false in your if statement, you will still continue through every for loop. So you will iterate through every seat, every time. If the price at the of the current seat never matches the user inputted price, you will go into an infinite loop. Try changing your inner for loop to
for (int j = 0; j < someCurrentLengthOfArray && searchFlag; j++)
That way you will check if the price matches and if you head an unspecified end of the array.
As was mentioned in one of the comments, why is this a 2D array?
Your while loop is outside the for loop, so all the replaces finish before you get back to the while loop. If you use #Dieter Lücking suggestion and just use a 1D array you can do this with one while loop
int i =0;
while (searchFlag == true)
{
// ..check for seats
if (seatFound)
{
searchFlag = false;
}
i++;
}
For 2D arrays you can still use the while loop method, it will just take two of them.
change your for loops:
for (int i = 0; i < 9 && searchFlag; i++)
{
for (int j = 0; j < 10 && searchFlag; j++)
{
if (Theater [i][j] == priceSelection)
{
Theater [i][j] = 0;
searchFlag = false;
}
}
}
The way they are now, they'll keep iterating through, until the end, no matter what. If you do as I showed above, they will break when searchFlag is set to true, and pull back out into the outer while loop, which will also then break.

Bubble Sort program does not output result

I am in a discrete mathematics class and one of the hw problems is to implement a bubble sort. Here's my futile attempt because it does not output the solution. Please advice. Thank you.
#include <iostream>
#include <cstdlib>
using namespace std;
void BubbleSort();
int array1[100] = {0};
int k;
int main()
{
cout << "Enter your numbers and when you are done, enter 0000:\n";
int x = 0;
int i;
while (i != 0000)
{
cin >> i;
array1[x] = i;
x++;
k = x;
}
BubbleSort();
system("pause");
return 0;
}
void BubbleSort(){
int temp;
for( int i = 0; i < k; i++ ){
if ( array1[i] > array1[i+1]){
temp = array1[i+1];
array1[i+1] = array1[i];
array1[i] = temp;
}
}
int x = 0;
while (x <= k)
{
cout << array1[x] << "\n";
x++;
}
}
Please only use basic programming techniques because this is my first programming class. Thank you.
Edit: fixed the relational operator. But now I get incorrect results.
while (x >! k)
This doesn't do what you think it does. If you want something that says "while x is not greater than k", you want <=. Since array1[k] isn't one of the elements you sorted, though, you probably want <.
while (x < k)
Note that for exists for loops like these:
for (int x = 0; x < k; x++) {
cout << array1[x] << "\n";
}
As for the new bug, you're only doing one round of bubbling in your bubble sort. You need another for loop. Also, i is never initialized in main, and i != 0000 isn't going to check whether the user literally entered 4 zeros. It'll only check whether the user's input was equal to the number 0.
The primary problem is here:
while (x >! k)
On the first iteration, the condition checks whether (0 > !k), and k is not 0, so !k is 0, so the condition is false and the loop never executes. Try using:
for (int x = 0; x < k; x++)
cout << array1[x] << "\n";
You also have a problem in the sort phase of your bubble sort; you only iterate through the data once, which is not enough to sort it, in general.
Finally, some design issues.
You should have one function to sort the data and a separate function to print it. Don't combine the two functions as you have done here.
Avoid global variables. Pass the array and its operational length to the sort function, and to the print function if you have one.