scanf() variable length specifier

前端 未结 4 855
心在旅途
心在旅途 2020-11-29 08:21

How can I use a variable to specify the max number of chars scanf() should read in?

For example using printf() you can use the * like so

4条回答
  •  自闭症患者
    2020-11-29 09:24

    You can't. You need to use something other than scanf(). A good and popular choice is fgets(), although its semantics are slightly different: fgets() will read a line of input, whereas scanf() with %s will read whitespace separated sequences of characters.

    To use fgets(), you'd want something like:

    fgets(string, MAXVAL, stdin);
    

    If for some reason you really want to use scanf(), have a look at this question: How to prevent scanf causing a buffer overflow in C?

提交回复
热议问题