【C语言】getchar函数 读入并输出任意长度字符串

来源:互联网 发布:三体 阶梯飞行器 知乎 编辑:程序博客网 时间:2024/05/16 08:25

主题来自 《C与指针》1.8.2:

编写一个程序,由控制台输入一个任意长度的字符串,标准输出读出该字符串。

思路:

定义一个字符串,使用字符串输入函数,输入字符串,再使用字符串输出函数输出该字符串。

但这时,使用字符串函数,就需要开辟一段空间,比如使用 fgets函数。需要固定长度就无法输入任意长度的字符串。

该换一种思路:

想到之前编写过一个程序(参考 【C语言】-->语法 fgets函数原理初探 ):

#include <stdio.h>#include <stdlib.h>int main(){int i = 0;char input[10];while (fgets(input,10,stdin) != NULL){  puts(input);  i ++;printf("i = %d\n",i);}return EXIT_SUCCESS;}

这个程序的输出是:

[root@localhost program]# ./getsDemohellohelloi = 1aaaaaaaaasssssssssddddddddfgggggghhhhhaaaaaaaaai = 2sssssssssi = 3ddddddddfi = 4gggggghhhi = 5hhi = 6
从中受到启发,当输入的值大于规定的值的时候,比如上例中的
aaaaaaaaasssssssssddddddddfgggggghhhhh
fgets函数并不会抛弃前9个字符之后所有的字符,而是会分次进行读取。

那我可以每次读一个字符,然后分次读取所有的字符,这样就OK了。

于是程序代码如下:

#include <stdio.h>#include <stdlib.h>int main(){char c;while ((c = getchar()) != '\n'){putchar(c);}printf("\n");return EXIT_SUCCESS;}

编译运行并输出为:

[root@localhost program]# gcc -g getcharDemo.c -o getcharDemo[root@localhost program]# ./getcharDemothis is a test! hello world!this is a test! hello world!

由此,成功输出了任意长度的字符串。

原创粉丝点击