美文网首页
【基础学习】C 读取字符串输入并输出

【基础学习】C 读取字符串输入并输出

作者: Jiubao | 来源:发表于2016-12-30 11:59 被阅读12次

读取字符串输入并输出,带上行号,不限制输入的行数和每行的量。

#include <stdio.h>

int main() 
{
    int line_count = 0;
    int ch;
    int at_beginning = 1;

    while ((ch = getchar()) != EOF)
    {
        if (at_beginning == 1)
        {
            at_beginning = 0;
            line_count += 1;
            printf("%d ", line_count);
        }

        putchar( ch );
        
        if (ch == '\n')
        {
            at_beginning = 1;
        }
        
    }

    return 0;
}

运行

➜  C ./a.out 
hello world
1 hello world
hello world
2 hello world
hello world
3 hello world
this is my input
4 this is my input
^C

主要通过 getchar() 和 putchar() 来做输入和输出,比较方便,能更好的实现需求。

相关文章

网友评论

      本文标题:【基础学习】C 读取字符串输入并输出

      本文链接:https://www.haomeiwen.com/subject/qrdmvttx.html