I have two scenarios using fgets below. Both scenarios are in the same file, as shown below.
struct sth
{
char str[10];
int num;
};
void getIt(struct sth **M){
char *b;
(*M)=malloc(sizeof(struct sth));
printf("give me an integer:");
fgets(b,1,stdin); // output must be an address
(*M)->num = atoi(b);
printf("give me a string:");
fgets((*M)->str,10,stdin);
}
int main(int argc, char const *argv[])
{
struct sth *myThing;
getIt(&myThing);
printf("Heres the string %s\n", myThing->str);
printf("Heres the num \n", myThing->num);
return 0;
}
Here is the output. Notice that it does not prompt the user for the integer, it just prints "give me an integer", and then moves directly on to the next print statement. Why does it do this?
give me an integer:give me a string:sdf
Heres the string sdf
Heres the num
This small problem is a larger problem in a bigger problem, so this is just a microcosm of the larger one.
Aucun commentaire:
Enregistrer un commentaire