Search code examples
cstringfgets

Multiple line input string using fgets


I want to input a multiple-line string using:

fgets(str,100,stdin)

and then output the same string.
For example:

Input:

my name is sandy
i am learning C

and the output should be:

my name is sandy
i am learning C

Solution

  • #include <stdio.h>
    #include <string.h>
    
    char *mfgets(char * restrict s, int n, FILE * restrict stream){
        int ch, i=0;
        if(n<1)return NULL;
        if(n==1){
            *s = '\0';
            return s;
        }
        while(EOF!=(ch=fgetc(stream))){
            s[i++] = ch;
            if(i == n - 1) break;
            if(ch == '\n'){
                char next = fgetc(stream);
                if(next == '\n')
                    break;
                else
                    ungetc(next, stream);
            }
        }
        s[i] = '\0';
        return i == 0 ? NULL : s;
    }
    
    int main(int argc, char *argv[]){
        char str[100];
        printf("input (only newline is end)\n");
        mfgets(str, 100, stdin);
        printf("%s", str);
    
        return 0;
    }