编程练习3

1.编写一个程序,统计从输入到文件结尾为止的字符数。

#include<iostream>
#include<stdio.h>
using namespace std;
int main(void)
{

	int count = 0 ;
	cout<<"please input characters:"<<endl;;
	while(getchar() != EOF)
		count++;
	cout<<"there are "<< count<<" characters"<<endl;
        return 0;
}


2.编写一个打印EOF值的程序。

#include<iostream>
#include<stdio.h>
using namespace std;


int main()
{
	cout<<"the value of EOF is: "<<EOF<<endl;
	return 0;
}


3.编写一个统计空格、制表符与换行符个数的程序。

#include<iostream>
#include<stdio.h>
using namespace std;


int main()
{
    char ch;
    int newline=0;
    int blank=0;
    int tab=0;
    cout<<"please input a string, end up with '#': "<<endl;
    while((ch=getchar())!='#')
    {
        if (ch=='\n') newline++;
        else if(ch==' ') blank++;
        else  if (ch=='\t')tab++;
    }
    cout<<"the NO.of the newline is :"<<newline<<endl;
    cout<<"the NO.of the blank is :"<<blank<<endl;
    cout<<"the NO.of the tab is :"<<tab<<endl;
    return 0;
}

4.编写一个程序,以每行一个单词的形式打印其输入。

<span style="font-size:18px;">#include<iostream>
#include<stdio.h>
using namespace std;

int main()
{
    int c;
    cout<<"please input a string, this program will output it one word in a line:"<<endl;
    while((c = getchar()) != EOF)
    {
        if(c != ' ' && c != '\n' && c !='\t')
        {
            putchar(c); //putchar函数的作用:向终端输出一个字符。
        }
        else if(c == ' ' || c== '\n' || c== '\t')
        {
            printf("\n");
            do
            {
                c = getchar();
            }
            while(c == ' '|| c== '\n' || c== '\t' );
            putchar(c);
        }
    }
    return 0;
}</span>


注意这里所使用的两个输入、输出函数:

putchar函数的作用:向终端输出一个字符。


getchar函数只能用于单个字符的输入,一次输入一个字符。程序的功能是输入一个字符,显示一个字符,回车换行,再输入并显示一个字符。而运行时字符是连续输入的,运行结果却是正确的,这是因为输入字符后,它们暂存于键盘的缓冲区中,然后由getchar函数从键盘缓冲区中一个一个的取出来。


另外有看到有人利用缓存的方法:

#include<stdio.h>
#include<conio.h>
#include <malloc.h>
#define BUFF_SIZE (2000)
int main()
{
long c;
char *buff;
int i=0;
static int j=1;
 
buff=(char *)malloc( BUFF_SIZE);
 
 
printf("请输入需要打印的字符串:\n");
while((c = getchar()) != EOF)
{
if(c ==' ' || c =='\t')
{
  buff[i++]='\n';
}
else
{
   buff[i++]=c;
}
  if (i>= BUFF_SIZE)
      {
           j++;
           buff=(char *)realloc(buff, BUFF_SIZE*j);
           if (buff==NULL)
                 {
                 fprintf(stderr,"Error:Not Enough Memorr!\n");       
                 return -1;
                 }
    }
 
}
buff[i]='\0';
puts(buff);
free(buff);
_getch();
return(0);
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值