注册 登录
编程论坛 C++教室

大家看这个程序哪里出错了?

tszhao 发布于 2008-03-08 13:03, 822 次点击
//作用是统计空格数,制表符,换行符的个数,能够通过编译,但是,出不来结果!!
#include <iostream>
using namespace std;
int main()
{
    int blank(0),tab(0),enter(0),other(0);
    char ch;
    while(ch=cin.get())
        switch(ch)
    {
        case ' ':++blank;break;
        case '\t':++tab;break;
        case '\n':++enter;break;
        default:++other;
    }
    cout<<"blank:"<<blank<<endl;
    cout<<"tab:"<<tab<<endl;
    cout<<"enter:"<<enter<<endl;
    cout<<"other:"<<other<<endl;
    return 0;
}
7 回复
#2
sunkaidong2008-03-08 13:08
#include<iostream>
main()
{
    int a[200]={0},max=0;
    char b[100],*p;
    p=b;
    gets(b);
    do
    {   
        if((int)*p>max)
          max=(int)*p;
        a[(int)*p++]++;
   
    }while(*p!='\0');
    for(int i=0;i<=max;i++)
        if(a[i]!=0)
    printf("a[%d]=%d",i,a[i]);//这样用就最好了printf("a[%c]=%d",i,a[i])
}
#3
tszhao2008-03-08 14:08
呵呵,谢谢楼上了,不过,好像解决的不是我这个问题哈!~~
#4
wfx_best2008-03-08 14:11
我在VC6.0上运行了你的程序
结果无法终止
问题出现在 while(ch=cin.get()) 这个语句上
改成 while(cin.get(ch)) 就正确了
原因是:
    while(ch=cin.get())这个语句中,while 实际检查的是 ch ,然而get() 返回值经转换后
再赋给 ch , ch 总是非空字符状态,于是 while 无法终止循环.
    换成 while(cin.get(ch)) ,while 检查的是 cin 流的状态,当你想结束程序时只要输入
Ctrl + Z 强制到达流末端就 OK 了.
#5
tszhao2008-03-08 14:17
谢谢楼上了,解释的也很棒!~~~眼泪哗哗的!!~~~
#6
wfx_best2008-03-08 14:25
不客气,这里是大家共同学习交流的地方
#7
lyc53055622008-03-09 13:17
貌似2楼的,看的不是很懂,能否解释下?
#8
sunkaidong2008-03-09 13:21
统计所有字符出现的个数.....把字符的acii取出来变成第二个数组的下标...以后遇到相同的字母只要把下标所在的数组元素加一.....
1