Reputation: 31
With C programming language,
I'm trying to read and store a string input to a char array which has fixed size[11].
When I type characters more than 10, the rest of the characters are sent to the next scanf.
So my question is,
Is there any way to limit the size of input can be typed?
Or, is there any way to cut off the rest of the characters when the input exceeds the size of a char array, not sending to the next scanf?
Or, should I just know how many characters to type?
Or, should I create conditions to prevent this issue?
int main(void)
{
char phoneNum[11];
char password[11];
printf("Enter the phone Number: ");
scanf("%10s", phoneNum);
printf("Enter the password: ");
scanf(" %10s", password);
printf("\n\n");
//Display
printf("Phone number: %s\n", phoneNum);
printf("Password : %s\n", password);
return 0;
}
/*
What I tried:
-input:
Enter the phone Number: 123-456-7890
Enter the password: // This part has been skipped.
-output:
Phone number: 123-456-78
Password: 90
What I expected:
-input:
Enter the phone Number: 123-456-7890
Enter the password: asdf12386945648
-output:
Phone number: 123-456-78
Password: asdf123869
*/
Upvotes: 2
Views: 2665
Reputation: 154280
Is there any way to limit the size of input can be typed?
No, code cannot prevent a user from typing. Instead code can limit the amount of input saved and potentially consume or exit with too much input.
Or, is there any way to cut off the rest of the characters when the input exceeds the size of a char array, not sending to the next scanf?
Yes. Good not to send it to the next input function. Deal with your problems here. A simple solution is
int read_input(char *destination, size_t sz) {
if (sz > INT_MAX) {
sz = INT_MAX;
}
if (fgets(destination, sz, stdin) == NULL) {
return EOF;
}
size_t len = strlen(destination);
if (len > 0 && destination[len-1] == '\n') { // lop off potential \n
destination[--len] = '\0';
}
if (len + 1 == sz) { // if more input ...
// let us consume it and toss it.
bool too_much = false;
int ch;
while ((ch = fgetc(stdin)) != '\n' || ch != EOF) {
too_much = true;
}
if (too_much) {
// Input exceeds expectations, take evasive action.
// Maybe print an error message and try again?
// For now, let us just exit.
fprintf("Input too long\n");
exit(EXIT_FAILURE);
}
}
return (int) len;
}
Or, should I just know how many characters to type?
User input is evil - expect the worst. Recommend to allow 2x the max legitimate input. Beyond that, something bad is up.
Or, should I create conditions to prevent this issue?
Cannot prevent, only cope with errant or nefarious input.
Tip: be generous in expected input size. 11
is too small for phoneNum[]
. Allow input to handle 2x of what you might expect, say 30, then qualify input. Insane input lengths are an attack.
Upvotes: 3