C - Reading from stdin as characters are typed

前端 未结 3 1346
醉梦人生
醉梦人生 2021-01-27 01:54

How do I fill an 80-character buffer with characters as they are being entered or until the carriage return key is pressed, or the buffer is full, whichever occurs first.

<
3条回答
  •  耶瑟儿~
    2021-01-27 02:48

    #include 
    ...
    char buf[80];
    int i;
    for (i = 0; i < sizeof(buf) - 1; i++)
    {
        int c = getchar();
        if ( (c == '\n') || (c == EOF) )
        {
            buf[i] = '\0';
            break;
        }
        buf[i] = c;
    }
    buf[sizeof(buf] - 1] = '\0';
    

提交回复
热议问题