c - 使用 fgets 多行输入字符串

标签 c string fgets

我想使用以下方式输入多行字符串:

fgets(str,100,stdin)

然后输出相同的字符串。
例如:

输入:

my name is sandy
i am learning C

输出应该是:

my name is sandy
i am learning C

最佳答案

#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;
}

关于c - 使用 fgets 多行输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17196897/

相关文章:

swift - 从时间戳创建字符串值时,发生崩溃 [Swift]

c++ - 识别字符串中的字符

c - 如何在 C 中检查 array[index] == "someString"?

c - C 中的 Null 终止字符数组以及使用 read 和 fgets 的区别

c - 在 RAM 中保存树/哈希表

algorithm - 在程序集中查找子字符串

c - 奇怪的 printf/pthread 错误?

c - strcmp 在用 fgets 读取的一行上

c++ - 按顺序移动数组中的元素

c - 为什么大括号周围的括号启用预处理器宏返回值