scanf string in c - why can i scan more than the char[] declaration?

后端 未结 4 1387
北荒
北荒 2021-01-16 10:15

I have a program where I need to scanf a string, which I know it will be only 2 characters long. (for example: \"ex\"). what is the proper way to do that?

I was goin

4条回答
  •  执念已碎
    2021-01-16 10:58

    The proper way to limit the input using scanf() is

    if (scanf("%2s", myStr) != 1) /* error */;
    

    But consider using fgets() rather than scanf()

    if (fgets(myStr, sizeof myStr, stdin) == NULL) /* error */;
    

提交回复
热议问题