I’m writing a program that works with files.
I need to be able to input data as structures, and eventually read it out.
The problem i have at the moment is with this code:
typedef struct {
char* name;
.....
}employeeRecord;
employeeRecord record;
char name[50];
if(choice == 1)
{
/*Name*/
printf("\nEnter the name:");
fgets(name,50,stdin);
record.nameLength = strlen(name) -1;
record.name = malloc(sizeof(char)*record.nameLength);
strcpy(record.name,name);
/*Other data, similar format...*/
If i want for example, name address and phone number, and ask for each in a row (so address is pretty much identical to above except replacing ‘name’ with address), i find it skips the input. What i mean is, I am given no chance to input it. The output is actually
Enter the name:
Enter the address: (and here is where it prompts me for input)
I tried your code and can’t reproduce the problem. The following code works just the way you would expect, it prompts for the name, wait for you to type the name, then prompts for the address, etc.
I’m wondering if you don’t need to read stdin and empty it before you prompt for more input?
Incidently, you want to add 1 to strlen(name), not subtract 1. or, if you want name stored in your record without a terminating null, then you need to use memcpy to copy the string into your record, not strcpy.
Edit:
I see from comments that you are using
scanfto read the choice value, this is leaving a \n in the input buffer which is then picked up by your firstfgetscall. What you should do instead is to use fgets to read in the choice line, and then sscanf to parse the value out of the input. like thisthat should make the whole issue of flushing stdin moot.