when running my main function and using scanf to get a char input, my program prints "4227467 device(s) found!" (input 1: 2, input 2:'B') and crashes after that. Wonder if its due to \n or any misunderstanding i may have towards scanf.
int main() {
int option;
printf("electronic devicedatabase (EDD)\n1 = Get database information\n2 = Search by port type\n3 = Search by current / power ratings\n=====\nInput: ");
scanf("%d",&option);
if (option ==1){
database_info();
}
else if (option == 2){
char port_type;
printf("Specify port type: ");
scanf("%c\n",&port_type);
search_port_type(port_type);
}
else if (option ==3){
float current_rating, power_rating;
printf("Specify current and power: ");
scanf("%f %f\n",¤t_rating, &power_rating);
search_current_power(current_rating, power_rating);
}
else{
printf("Invalid input!\n");
};
return 0;
}
void search_port_type(char port_type) {
int index[5],counter = 0,i = 0;
for (i=0; i<5; i++){
if (dev_database[i].port_type == port_type ){
index[counter]=i;
counter++;
}
}
printf("%d device(s) found!\n",counter);
for (i=0; i<counter; i++){
print_device(index[i]);
}
return;
}
void search_current_power(float current, float power) {
int index[5],counter = 0,i = 0;
for (i=0; i<5; i++){
if (dev_database[i].current_rating == current && dev_database[i].power_rating == power){
index[counter]=i;
counter++;
}
}
printf("%d device(s) found!\n",counter);
for (i=0; i<counter; i++){
print_device(index[i]);
}
return;
}
Attached is the hyperlink to the full code, ive check each individual function and its working as intended. https://onlinegdb.com/BkGxu3u1z
Any help is greatly appreciated, thank you!
Edit: initialised automatic/local variable in the blocks. Option 3 works now! However option 2 still does not work and always give "0 device(s) found!" when giving 'B' as an input.
Final edit: Im was wrong with giving 'B' as using scanf("%c\n",&port_type) does not require the ' '.
sample data:
struct device {
int ports;
char port_type;
float cost;
int cpu_cores;
int chips;
struct {
int version;
int year;
char manufacturer[10];
} make;
float current_rating, power_rating;
};
struct device dev_database[5] = {
{5, 'B', 73.45, 4, 7, {2, 2015, "Intel"}, 3.1, 1.2},
{5, 'A', 70.00, 2, 5, {1, 2010, "Micron"}, 2.0, 1.5},
{5, 'B', 65.00, 2, 5, {1, 2011, "Intel"}, 3.0, 1.5},
{5, 'C', 80.00, 8, 7, {1, 2015, "Motorola"}, 2.5, 1.0},
{5, 'A', 70.00, 2, 5, {3, 2012, "Intel"}, 3.0, 1.3}
};