从杭电OJ1219 到getchar 以及EOF

来源:互联网 发布:淘宝开店推广费用 编辑:程序博客网 时间:2024/06/05 03:44

Problem Description
Ignatius is doing his homework now. The teacher gives him some articles and asks him to tell how many times each letter appears.

It's really easy, isn't it? So come on and AC ME.
 

Input
Each article consists of just one line, and all the letters are in lowercase. You just have to count the number of each letter, so do not pay attention to other characters. The length of article is at most 100000. Process to the end of file.

Note: the problem has multi-cases, and you may use "while(gets(buf)){...}" to process to the end of file.
 

Output
For each article, you have to tell how many times each letter appears. The output format is like "X:N". 

Output a blank line after each test case. More details in sample output.
 

Sample Input
hello, this is my first acm contest!work hard for hdu acm.
 

Sample Output
a:1b:0c:2d:0e:2f:1g:0h:2i:3j:0k:0l:2m:2n:1o:2p:0q:0r:1s:4t:4u:0v:0w:0x:0y:1z:0a:2b:0c:1d:2e:0f:1g:0h:2i:0j:0k:1l:0m:1n:0o:2p:0q:0r:3s:0t:0u:1v:0w:1x:0y:0z:0
 

Author
Ignatius.L






此题着重判断回车换行和文件结束末尾,通过查阅资料发现,char 类型的变量c,通过赋值语句c=getchar,是不能够获得有关文件结束符EOF的值的。原因在于:EOF的实际值为-1,而char类型是不能被赋值为负数的。所以更加标准的写法应当是:

int c;

c=getchar();

现在只要判断c是否等于-1,就可以判断是否到了文件的末尾了。

更多有关getchar和EOF的内容,参见http://www.jb51.net/article/36848.htm



AC代码

#include <iostream>#include <stdio.h>using namespace std;int main(){//freopen("D:\\input.txt","r",stdin);//freopen("D:\\output.txt","w",stdout);int A[26]={0};int c;c=getchar();while(c!=-1){memset(A,0,sizeof(A));while((char)c!='\n'&&c!=-1){if(c>='a'&&c<='z')A[c-'a']++;c=getchar();}for(int i=0;i<26;i++){printf("%c:%d\n",'a'+i,A[i]);//cout<<'a'+i<<':'<<A[i]<<endl;}if(c==-1)break;cout<<endl;c=getchar();}}


0 0
原创粉丝点击