C getchar 统计输入的行数,单词数,字符数

#include <stdio.h>
#include <stdio.h>
/* copy input to output; 1st version */
//getchar()是stdio.h中的库函数,它的作用是从stdin流中读入一个字符,也就是说,如果stdin有数据的话不用输入它就可以直接读取了,
//第一次调用getchar()时,确实需要人工的输入,但是如果你输了多个字符,以后的getchar()再执行时就会直接从缓冲区中读取了
//getchar
//getchar可用宏实现:#define getchar() getc(stdin)。getchar有一个int型的返回值。
//当程序调用getchar时.程序就等着用户按键。用户输入的字符被存放在键盘缓冲区中。
//直到用户按回车为止(回车字符也放在缓冲区中)。
//当用户键入回车之后,getchar才开始从stdin流中每次读入一个字符。
//getchar函数的返回值是用户输入的字符的ASCII码,若文件结尾(End - Of - File)则返回 - 1(EOF),且将用户输入的字符回显到屏幕。
//如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取。
//也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完后,才等待用户按键。
void main()
{
	//int c;
	//c = getchar();//getchar遇到回车返回,返回第一个字符的ascii值,如果遇到ctrl+c或ctrl+z返回EOF。一次可以输入多个字符,下次getchar可以直接从缓冲区读取
	//while (c != EOF) {
	//	putchar(c);
	//	c = getchar();
	//}

	int c;
	while ((c = getchar()) != EOF)
		putchar(c);
}

 

// 统计输入的行数,单词数,字符数
void main()
{
	int c, nl, nw, nc, state;
	state = 1;//单词外
	nl = nw = nc = 0;
	while ((c = getchar()) != EOF) {
		++nc;
		if (c == '\n')
			++nl;
		if (c == ' ' || c == '\n' || c == '\t')
			state = 1;
		else if (state == 1) {
			state = 0;//单词外
			++nw;
		}
	}
	printf("%d %d %d\n", nl, nw, nc);
}

#include <stdio.h>
#define MAXLINE 1000	// maximum input line length
// 程序读入一组文本行,并把最长的文本行打印出来
//算法的基本框架:
//while(还有未处理的行)
//if(该行比已处理的最长行还长)
	//保存改行为最长行
	//保存改行的长度
//打印最长行

int getline(char line[], int maxline);
void copy(char to[],char from[]);
/* print the longest input line */
void main()
{
	int len;
	int max;
	char line[MAXLINE];
	char longest[MAXLINE];
	max = 0;
	while ((len = getline(line, MAXLINE)) > 0)
	{
		if (len > max)
		{
			max = len;
			copy(longest, line);
		}
	}
	if (max > 0)
	{
		printf("%s",longest);
	}
}

/* read a line into s,return length */
int getline(char s[], int lim)
{
	int c, i;
	for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
	{
		s[i] = c;
		if (c == '\n')
		{
			s[i] = c;
			++i;
		}
	}
	s[i] = '\0';
	return i;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
	int i;
	i = 0;
	while ((to[i] = from[i]) != '\0')
		++i;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值