I'm new in the C world, and I’ve a problem with fgets()
function.
I googled almost 2 hours my error, and found different solutions but no one worked.
My class is too big for just show every parts of it, but let me show you the problematic part:
//... kivansag is a struct(!)
if(check == 1){
char name;
printf("Please give me your nickname!\n");
scanf("%s", &name);
strcpy(kivansag.name,&name);
char city;
printf("Please give me your city!\n");
scanf("%s", &city);
strcpy(kivansag.city,&city);
char *address = malloc(100);
printf("Please give me your address!\n");
fgets(address,100,stdin);
if((strlen(address)>0) && address[strlen(address)-1] == '\n'){
address[strlen(address)-1] = '\0';
}
strcpy(kivansag.address,address);
free(address);
}//...
The problem is: Every time I run this code, the running server is skipping fgets()
after it wrote out "give me your address", and do the following function.
May I get any suggestions?
UPDATED:
Now I have only this:
printf("Please give me your address!\n");
fgets(kivansag.address,sizeof(kivansag.address),stdin);
if((strlen(kivansag.address)>0) && kivansag.address[strlen(kivansag.address)-1] == '\n'){
kivansag.address[strlen(kivansag.address)-1] = '\0';
}
the struct seems like this:
struct Kivansag{
//...
char address[100];
};
And yeah, still skipping my part... I tried to use fflush(stdin)
too, to make sure everything is clear, but not worked.