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

主题来自 《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]# ./getsDemo
hello
hello

i = 1
aaaaaaaaasssssssssddddddddfgggggghhhhh
aaaaaaaaa
i = 2
sssssssss
i = 3
ddddddddf
i = 4
gggggghhh
i = 5
hh

i = 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]# ./getcharDemo
this is a test! hello world!
this is a test! hello world!

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值