c - How do I use scanf to limit the user from entering a string no larger than the array? -
how use scanf limit user entering string no larger array?
what i've tried far is:
#include<stdio.h> int main() { const maxstring = 5; char arr[maxstring] = {}; printf("enter string: \n"); scanf("%*s", maxstring-1, arr); return 0; }
but doesn't seem work.
if want have user enter string terminated newline, it's idea use fgets
instead of scanf
. function fgets
receives parameter length of buffer , won't overrun buffer. can check result figure out if truncation occured. consult documentation of c language implementation more details.
fgets(arr, maxstring, stdin);
Comments
Post a Comment