So, I'm totally new to C and I'm having some struggle with some basic concepts, mainly when it is about buffer, memory, and string creation. So, I have this assignment from College where I need to make an Array of Structs called Vehicles, and during the execution of the program I must take inputs from the user about the Vehicle mark, year, and licensePlate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Vehicles {
char mark[20];
int modelYear;
char licensePlate[8];
};
int main() {
const int DEFAULT_SIZE = 10;
struct Vehicles vehiclesArr[DEFAULT_SIZE];
for(int i = 0; i < DEFAULT_SIZE ; i++) {
memcpy(vehiclesArr[i].mark, "", 1);
vehiclesArr[i].modelYear = 0;
memcpy(vehiclesArr[i].licensePlate, "", 1);
}
int choice = 0;
int counter = 0;
printf("Hello Professor, my name is Henrique and in this program I will be your guide.\n");
while (choice != 4) {
printf("So, what it will be for today?\n Choose a valid option.\n");
printf("0. Create a new Vehicle.\n");
printf("1. List all saved vehicles.\n");
printf("2. Update a saved vehicle.\n");
printf("3. Delete a saved vehicle.\n");
printf("4. Quit Program.\n");
scanf("%d", &choice);
switch (choice) {
case 0:
if (counter < 10) {
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
printf("\n Choose the model year \n");
scanf("%d", &vehiclesArr[counter].modelYear);
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
counter++;
break;
} else {
printf("\n Storage limit reached.");
}
case 1:
for(int i = 0; i < DEFAULT_SIZE; i++) {
printf("\nModel: %s", vehiclesArr[i].mark);
printf("\nYear: %d", vehiclesArr[i].modelYear);
printf("\nLicense Plate: %s", vehiclesArr[i].licensePlate);
}
break;
case 2:
break;
case 3:
break;
case 4:
printf("Gently finishing program... Bye Bye!");
break;
default:
printf("\nWhat? The number must be between 0 and 4\n");
}
}
}
The problem is that, when I execute the program and press 0, the program just skip the user input on those two lines bellow:
...
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
...
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
...
I'm trying to figure out what is happening been a while now, the only thing that works is if I use "%s", but I need the program to handle when user inputs an space character.
Can someone help me, and please explain why is this happening? This is my first question so I would appreciate if you guys also tell me how I can make my questions better.