Reading strings in C

前端 未结 6 1774
轮回少年
轮回少年 2021-01-14 03:52

If I was using C gets(), and I was reading a string from the user, but I have no idea how big of a buffer I need, and the input could be very large. Is there a way I can det

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 04:38

    Don't use gets(). Use fgets(), and over approximate how much buffer space you will need.

    The advantage of fgets is that if you go over, it will only write that max number of characters, and it won't clobber the memory of another part of your program.

    char buff[100];
    fgets(buff,100,stdin);
    

    will only read up to 99 characters or until it hits a `'\n'. If there's room, it will read the newline into the array.

提交回复
热议问题