Something that I thought that would be pretty basic has me stumped.
If I have a char
array char menuInput[3];
and do fgets(menuInput,3,stdin);
, I can easily check if they entered nothing:
if(menuInput[0]=='\n')
{
printf("******You made no selection.******");
}
Or if they entered too many (in this case, more than one) characters:
else if(menuInput[1]!='\n')
{
printf("******Invalid Selection: Please enter a single digit option.******");
break;
}
In that case, the user is entering either no characters, exactly the right amount (one), or too many.
What is giving me trouble is checking when they could either enter no characters, up to n
amount, or too many.
If I have char surname[SURNAME_MAX + 1];
, and use fgets(surname,SURNAME_MAX + 1,stdin);
where SURNAME_MAX
is 12, I can't work out how to check whether the input falls within the 'acceptable' range.
I can easily see if the user has inputted anything at all (if surname[0]='\n'
) and if they have entered exactly 12 characters (with the 13th being the '\n'
).
I think the crux of things is here is just making sure that, somewhere, surname[SURNAME_MAX + 1]
contains '\n', but I don't know how to do that in C.
Regards,
Doug
EDIT: Ok, I'm going with @R Sahu's answer, but am having trouble making it work properly.
I'm expecting, at most, the 12 characters defined by SURNAME_MAX.
This should mean that, by that answer, my array should be surname[SURNAME_MAX+3]
("need at least SURNAME_MAX+2 just to store the newline and the terminating null character")
Then I fgets(surname,SURNAME_MAX + 3,stdin);
and then is it supposed to be:
while(strlen(surname)>SURNAME_MAX+2);
{
printf("Input is too long!\n");
printf("Surname (1-12 characters): ");
fgets(surname,SURNAME_MAX + 2,stdin);
}
?
Is that the correct way of implementing the answer?
It looks right to me, but, no matter what I enter, I'm getting the "Input is too long!" message.
EDIT 2: My bad, had some code in the wrong place, all good now.
You said:
What is giving me trouble is checking when they could either enter no characters, up to n amount, or too many.
My suggestion: If you are expecting to see at most N
characters, create an array whose size is larger than N+2
. You need at least N+2
just to store the newline and the terminating null character, and use fgets
on that string. If the length of the string is greater than N+1
, then you know they entered too many characters. Detecting whether they entered too few characters is simple. I think you will be able to figure it out.