'Search function does not find the first element in the struct
I was asked to code a function for class that would allow the user to search through an array of structs. The function asks the user to enter the ID, and then the other parts of the struct should display if found. This works perfectly, except for the first element ([0]) in the array. I keep getting a return of -1, or a "not found", and I can't seem to figure out why.
int i = 0;
for(; i < totalEng; i++)//loop to find the engine ID
{
if(search == (peng + i)->id)
return i;
}
return - 1;
This is the search function that works for every ID but this one
(peng + 0)->id = 111;
(peng + 0)->hp = 500;
(peng + 0)->size = 4.5;
This is my function which populates the array:
void populateEng(engine* peng)
{
(peng + 0)->id = 111;
(peng + 0)->hp = 500;
(peng + 0)->size = 4.5;
(peng + 1)->id = 222;
(peng + 1)->hp = 120;
(peng + 1)->size = 1.2;
(peng + 2)->id = 333;
(peng + 2)->hp = 300;
(peng + 2)->size = 6.5;
(peng + 3)->id = 444;
(peng + 3)->hp = 95;
(peng + 3)->size = 1.5;
(peng + 4)->id = 555;
(peng + 4)->hp = 200;
(peng + 4)->size = 2.5;
(peng + 5)->id = 666;
(peng + 5)->hp = 700;
(peng + 5)->size = 5.0;
}
And this is the search function in its entirety:
int searchEng(engine* peng, int totalEng)
{
char input[5];
char* pinput = NULL;
int i = 0;
int length = 0;
int search = 0;
printf("Enter the ID of the engine you wish to search for: ");
pinput = fgets(input, buffer, stdin);
length = strlen(input);
for(; i < length - 1; i++) // making sure the user enters only 3-4 numbers
{
if(length > 5 || length < 3)
{
i = 0;
printf("Invalid input. Please enter up to 4 numbers only: ");
pinput = fgets(input, buffer, stdin);
length = strlen(input);
}
if(input[i] < '0' || input[i] > '9')
{
i = 0;
printf("Invalid input. Please enter up to 4 numbers only: ");
pinput = fgets(input, buffer, stdin);
length = strlen(input);
}
}
search = atoi(input); // converting the input into an integer to search
for(i = 0; i < totalEng; i++)//loop to find the engine ID
{
if(search == (peng + i)->id)
return i;
}
return - 1;
}
I have the struct and the array defined as this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define buffer 10
struct engine
{
int id;
int hp;
double size;
}typedef engine;
int main()
{
engine eng[100];
engine* peng = &eng[0];
// ...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
