comments in code show what is going on ...
Code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
/* Data av typen fordon och person */
typedef struct fordon {
char namn[40];
char marke[25];
char fordonstyp[25];
int registeringsnummer;
} fordon;
fordon f[10];
typedef struct person {
char id[40];
int alder;
} person;
person p;
/* Funktion lägg till fordon */
bool add(fordon* f) {
fordon tmp;
printf("Enter name: ");
scanf("%s", tmp.namn);
/* Läs in allt data och lägg i tmp */
*f = tmp;
return true; // Allt gick bra
}
int main() {
/* switch meny */
int val = 0, i = 0 ; // here make zero
while(val != 6){
printf("\n1. Add a vehicle");
printf("\n2. Remove a vehicle");
printf("\n3. Sort by car brand");
printf("\n4. Print information about a vehicle");
printf("\n5. Print out vehicle directory");
printf("\n6. End\n");
printf("Enter a choice (1-6): ");
// this is the biggest problem right here
//does does not stop the loop
// after hiting 10
scanf("%d", &val);
switch(val){
case 1:
// i = 0; // moved out of loop
/*
while( f[i].namn[0] != '\0' && i < 10) // i is 0 - 9 = 10
{
i++;
}
if(i == 10 && f[9].namn[0] != '\0')
{
printf("\n Directory is full\n");
}
else
{
add(&f[i]);
}
* */
// logically all you need to do is keep
// track of i because it is checked to match the size of your
// array.
if ( i < 10) // goes up to 9 then stops giving you 0 - 9 = 10
{
add(&f[i]);
i++;
printf("i = %d\n", i);
}
else
{
printf("\n Directory is full\n");
// val = 6; //kicks it completely out of loop
}
break; // takes it back up to menu but that scanf does not
// hold down the fort so it lets it continue to loop continuously
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
for(i=0; i<10; i++){
printf("%d.%s ", i, f[i].namn);}
break;
case 6:
break;
default:
printf("\nWrong! Select one of the options 1-6.\n");
}
}
for ( int d = 0; d < 10; d++)
printf("d %d: %s\n", d+1, f[d].namn);
return 0;
}
results with val = 6;
Code:
6. End
Enter a choice (1-6): 1
Directory is full
d 1: f
d 2: f
d 3: g
d 4: d
d 5: b
d 6: h
d 7: t
d 8: n
d 9: f
d 10: d
OK I just tried this... adding this in your switch with that code I posted
Code:
else
{
printf("\n Directory is full\n");
// val = 6; //kicks it completely out of loop
val = 0;
}
took it up to 10 and got this to happen.
Code:
Enter a choice (1-6): 1
Directory is full
1. Add a vehicle
2. Remove a vehicle
3. Sort by car brand
4. Print information about a vehicle
5. Print out vehicle directory
6. End
Enter a choice (1-6):
on the 11th try to add it did that and stuck no loopy gone mad. is that logically ok? you could tweak it from there I suppose.
so that maybe hopefully will solved your issue with it.
maybe add
Code:
int main() {
memset(f, 0, 10 * sizeof (fordon));
memset(&p, 0, sizeof (person));
to initialize your struct's