How to Check Values in an Array

I have a program in which the user inputs data and it gets stored into an array. However, no two of the same values can be stored in the array.
I have to write a function to check if the value enters already exists in the array. if it does, it'll return true. if it doesn't, return false.

my main code is:
char city;
do {
n++;
cout<<endl<<"Please enter the city code: ";
cin>> city;
city = toupper(city);
while (cityExists (city, name, n)) {
cout<<endl<<"ERROR: city already exists!"<<endl<<endl;
cout<<"Please enter the city code: ";
cin>>city;
city = toupper(city);
}
name[n] = city;

the function cityExists is:
bool cityExists(char city, char name[], int n) {
int i=0;
bool check1= false;
for (i=0; i<=n; i++) {
if (city == 'name[i]'){
check1 = true;
}
else { }
}
return check1;
}


the function also can't differentiate between upper and lower case city codes. like, 'a' is the same as 'A'. that's why the toupper() function is there.

Please help! thanks!

You know you can't just "add" elements to an array...you need to set a size first, otherwise you will be accessing out of range data which is very bad. If you don't know how much will be put in, use a vector.
well, i want it to add the value in name[i], if it already doesn't exist in say name[i-1] or a previous array value.
there is a set size, but i don't think that's important. the bool function should only check up until n, the number of values entered.
Well then just use a for loop like you have...it looks fine to me.
it still doesn't work though. it's returning false to the function instead of true if there's another entry.
Whats the initial value of n and where have you declared its type?
Where have you initialized the array and its size?

Is this the full code? Didn't your compiler give you any errors or warnings?
int n=-1;
char name[100];

sorry no, that wasn't the full code, just two functions of it. it's really long otherwise, and that was the only part i was having trouble with.
and no, the compiler didn't give me any errors or warnings..
For the cityExists() function, what value are you puting into name?

I'd say change your cityExist function to return true if value is found i.e.

1
2
3
4
5
6
7
8
9
10
bool cityExists(char city, char name[], int n) {

   int i = 0;

   for (i=0; i<=n; i++) {
      if (city == name[i]) {
         return true;
      }
      return false;
}
Topic archived. No new replies allowed.