'Returning the index of a stringarray value
im trying to return the index of a string in my array upon I get it as input, I seem to get 9 for every color I input can you help me fix this?
ps "this may seem obvious but Im not very experienced"
int FindIndex( const char a[][10], int size, char value[10] )
{
int index = 0;
while ( index < size && a[index] != value ) ++index;
printf("%d", index);
return ( index == size ? -1 : index );
}
int main()
{
char str[10];
char colors[][10] = {
"BLACK","BROWN",
"RED","ORANGE",
"YELLOW","GREEN",
"BLUE","VIOLET",
"GREY","WHITE"
};
printf("what resistor?\n");
scanf("%s",str);
FindIndex(colors,9,str);
}
Solution 1:[1]
int FindIndex( const char a[][10], int size, char value[10] )
{
int found = -1;
for(int i = 0; i < size; ++i) {
if(strcmp(a[i], value) == 0) {
found = i;
break;
}
}
printf("%d", found);
return found;
}
Or as suggested by @Aconcagua, in a more concise form:
int FindIndex( const char a[][10], int size, char value[10] )
{
for(int i = 0; i < size; ++i) {
if(strcmp(a[i], value) == 0) {
printf("%d", i);
return i;
}
}
return -1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
