scanf() variable length specifier

前端 未结 4 858
心在旅途
心在旅途 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:19

    Kernighan and Pike recommend using snprintf() to create the format string. I developed this idea into a method that safely reads strings:

    void scan_string(char * buffer, unsigned length) {
        char format[12]; // Support max int value for the format %s
        snprintf(format, sizeof(format), "%%%ds", length - 1); // Generate format
        scanf(format, buffer);
    }
    
    int main() {
      char string[5];
      scan_string(string, sizeof(string));
      printf("%s\n", string);
    }
    

提交回复
热议问题