I am currently a student learning c, and I had to make a struct loop to collect info for 10 customers.
Code:
#include <stdio.h>
#include <stdlib.h>
#define NAME_LEN 10
int main() {
typedef struct
{
char firstName[30];
char lastName[30];
char street[35];
char city[20];
char state[3];
int zip [15];
char phone[15];
int accountId[40];
} Customer;
int myIntArray[NAME_LEN] = {0};
Customer custArray[NAME_LEN];
int i = 0;
for(i = 0; i < NAME_LEN; ++i)
{
printf("Enter Information for Customer %d\n", i + 1);
printf ("First Name: ");
fgets (custArray[i].firstName, 30, stdin);
printf ("Last Name: ");
fgets (custArray[i].lastName, 30, stdin);
printf ("Address: ");
fgets (custArray[i].street, 35, stdin);
printf ("City: ");
fgets (custArray[i].city, 20, stdin);
printf ("State Code (ex. CO for Colorado, OR for Oregon): ");
fgets (custArray[i].state, 3, stdin);
printf ("Zip Code: ");
fgets(custArray[i].zip, 15, stdin);
printf("Phone Number: ");
fgets (custArray[i].phone, 15, stdin);
printf("Account Number: ");
fgets (custArray[i].accountId, 40, stdin);
}
return(0);
}
It mostly works, but I'm having a really weird issue. If I enter more than a single character in the "State Code (ex. CO for Colorado, OR for Oregon): " entry, the next thing that pops up is
Zip Code: Phone Number:
It works fine if I just press enter or enter a single character, but not 2+. I realize I can just increase the array size to 4, but I'd like to know why this is happening. Shouldn't an array of 3 be capable of holding the two characters and the '\n'?