Reading strings in C

前端 未结 6 1848
轮回少年
轮回少年 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:13

    Allocate your buffer dynamically and use fgets. If you fill the buffer right up then it wasn't big enough so grow it using realloc and then fgets again (but write to the end of the string to maintain what you've already grabbed). Keep doing that until your buffer is larger than the input:

    buffer = malloc(bufsize);
    do{
        GotStuff = fgets(buffer, bufsize, stdin))
        buffer[bufsize-1] = 0;
        if (GotStuff && (strlen(buffer) >= bufsize-1))
        {
            oldsize = bufsize;
            buffer = realloc(bufsize *= 2);
            GotStuff = fgets( buffer + oldsize, bufsize - oldsize, stdin )
            buffer[bufsize-1] = 0;
        }
    } while (GotStuff && (strlen(buffer) >= bufsize-1));
    

提交回复
热议问题