Hi All,
I am very new to C and have been working my way through a few C books with the aim of getting more knowledge in programming. However I have hit a wall and I am not sure how to get over it.
I have the following code, it is quite simple.
I understand how this code works without any problems. I do have issues regarding input though.
If I enter more that the allowed characters using the fgets function then the first myCat.name[i] is terminated with \0, this is what I would expect. The problem is that the STDIO buffer retains my extra input and enters it into the next fgets() function. How can I stop this?
Also how can I do some error checking on the fgets() functions to see if the user entered more than needed input and consequentaly reset the character array before asking them again?
I was thinking of finding the character array length and if it is equal to 19 checking the last element for the \0 terminator? I think this would do it but I am unsure how to clear the array so that it is empty and does not contain "junk" data.
Any help is greatly appreciated.
I am very new to C and have been working my way through a few C books with the aim of getting more knowledge in programming. However I have hit a wall and I am not sure how to get over it.
I have the following code, it is quite simple.
Code:
#include <stdio.h>
struct cat
{
int age;
int height;
char name[20];
char father[20];
char mother[20];
};
int main()
{
struct cat myCat[2];
int i = 0;
for(i = 0; i < 2 ; i++ )
{
printf("What is your cats name?\n");
fgets(myCat[i].name, 20, stdin);
}
for(i = 0; i < 2 ; i++ )
{
printf("%s", myCat[i].name);
}
return 0;
}
If I enter more that the allowed characters using the fgets function then the first myCat.name[i] is terminated with \0, this is what I would expect. The problem is that the STDIO buffer retains my extra input and enters it into the next fgets() function. How can I stop this?
Also how can I do some error checking on the fgets() functions to see if the user entered more than needed input and consequentaly reset the character array before asking them again?
I was thinking of finding the character array length and if it is equal to 19 checking the last element for the \0 terminator? I think this would do it but I am unsure how to clear the array so that it is empty and does not contain "junk" data.
Any help is greatly appreciated.
Comment