【C语言】getchar函数 读入并输出任意长度字符串
2013-03-29 22:09
267 查看
主题来自 《C与指针》1.8.2:
编写一个程序,由控制台输入一个任意长度的字符串,标准输出读出该字符串。
思路:
定义一个字符串,使用字符串输入函数,输入字符串,再使用字符串输出函数输出该字符串。
但这时,使用字符串函数,就需要开辟一段空间,比如使用 fgets函数。需要固定长度就无法输入任意长度的字符串。
该换一种思路:
想到之前编写过一个程序(参考
【C语言】-->语法 fgets函数原理初探 ):
这个程序的输出是:
那我可以每次读一个字符,然后分次读取所有的字符,这样就OK了。
于是程序代码如下:
编译运行并输出为:
由此,成功输出了任意长度的字符串。
编写一个程序,由控制台输入一个任意长度的字符串,标准输出读出该字符串。
思路:
定义一个字符串,使用字符串输入函数,输入字符串,再使用字符串输出函数输出该字符串。
但这时,使用字符串函数,就需要开辟一段空间,比如使用 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从中受到启发,当输入的值大于规定的值的时候,比如上例中的
aaaaaaaaasssssssssddddddddfgggggghhhhhfgets函数并不会抛弃前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!
由此,成功输出了任意长度的字符串。
相关文章推荐
- c语言:用getchar函数读入两个字符给c1,c2,用putchar和printf输出。思考问题
- c语言:用getchar函数读入两个字符给c1,c2,用putchar和printf输出。思考问题
- C语言---递归反向输出任意长度的字符串
- C语言---递归反向输出任意长度的字符串
- 运用递归输入一串任意长度的字符并输出
- 读入一个字符串(长度不大于100,不包括换行符’\n’),删去字符串中相同的排在后面的字符并输出。
- 要求编写程序,读入5个字符串,按由小到大的顺序输出。 (2)功能要求 ①输入格式:输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
- 0804使用信号,读入终端输入的字符,并将其中的小写字母转换成大写字母后输出
- 【c语言】从键盘输入BOY三个字符,然后把它们输出到屏幕
- C语言—正序,逆序输出任意整数的每一个数字
- 关于键盘输入、缓冲输入、读入字符、解析C语言编程对缓冲区的理解
- 【C语言】在字符串中找出第一个只出现一次的字符。 如输入“abaccdeff”,则输出'b'。
- C语言:读入N名学生的成绩,将获得某一给定分数的学生人数输出
- c语言-输入任意长度字符串
- 【C语言】编写一个程序,从标准输入读取几行输入。每行输入都要打印到标准输出上,前面加上行号。编写这个程序的时候要使这个程序能够处理的输入行的长度没有限制。
- C语言-输入任意长度字符串
- c语言字符输出格式化
- 编写函数,对标准输入进行扫描,并对“the”出现的次数进行计数。 进行比较时应区分大小写。认为一个单词有一个或多个空格字符分隔, 并且输入行在长度上不会超过100个字符,计数结果输出。
- C语言 字符格式化输出
- C语言输出单个汉字字符