I'm starting with this language and I can't find anywhere how to check the data of an array. As you can see in my code, I want the if to analyze the selection variable and compare it with the data inside the names[] array, but I can't find a way to do this.
#include<string>
#include<iostream>
using namespace std;
int main(){
string nombres[3] = {"alejandro","jose","juan"};
string seleccion;
cout<<"Ingrese su nombre ";cin>>seleccion;
if (seleccion==nombres[]){
cout<<"Bienvenido";
}
else {
cout<<"Error";
}
return 0;
}
What you have to do to check values in an array is loop through it and check one by one. To loop through it in this case you can use a for or a while .
I give you the example with a for
The for has 3 parts: the initialization
int i=0
, the conditioni<3
and an updatei++
which is similar to writingi=i+1
. This will cause the code inside to be executed 3 times (that is, 3 if will be executed, one for each value of the names array).Within the
if
only thing that changes isnombres[i]
, making use of[i]
we access each of the values of the array.You can find more information in the c++ documentation https://en.cppreference.com/w/cpp/language/for or in various tutorials on the internet
In your case, an ordered list , use binary_search from
#include<algorithm>
:For unordered lists, use find .
Saying that you need to " check the data in an array " is very vague and ambiguous. From what you show in your code we can deduce that what you want is to search for a data within an array 1 , you could do it by going through the elements and comparing with the data:
Roughly speaking, that's exactly what
std::find
the header function does<algorithm>
: