c语言输出字体的大小的函数,【C语言】getchar函数 读入并输出任意长度字符串...
主题来自 《C与指针》1.8.2:
编写一个程序,由控制台输入一个任意长度的字符串,标准输出读出该字符串。
思路:
定义一个字符串,使用字符串输入函数,输入字符串,再使用字符串输出函数输出该字符串。
但这时,使用字符串函数,就需要开辟一段空间,比如使用 fgets函数。需要固定长度就无法输入任意长度的字符串。
该换一种思路:
#include
#include
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
#include
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!
由此,成功输出了任意长度的字符串。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
