您的位置:首页 > 编程语言 > C语言/C++

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

2013-03-29 22:09 267 查看
主题来自 《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!


由此,成功输出了任意长度的字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐