cin.getline()在while循环中不起作用

时间:2014-03-31 07:05:12

标签: c++

这是我的程序,用于查找多行字符串中的字符频率:

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string>
using namespace std;
void occ(char *s);

int main()
{
     string s;
    char p[355],a[80];
    int i,j,n,l=0;
    char ch;
    cout<<"Enter a string:";
    gets(p);
      while(ch=='y' || ch=='Y')
    {
        cout<<"Enter string:";
          gets(a,80);
         strcat(p,a);
        cout<<"\nDo you want to enter another string (y/n):";
          cin>>ch;
    }
    occ(p);
    return 0;
}

void occ(char s[])
{
    int i;
    char ch,m[80];
    int j,n=0,k,l,c;
    m[n]='\0';
    l=strlen(s);
    for(int i=0; s[i]!='\0'; i++)
    {
        int flag=0;
        ch=s[i];
        for(int k=0; m[k]!='\0'; k++)
        {
            if(m[k]==ch)
                flag=1;
        }
        c=0;j=0;
        if(flag!=1)
        {
            m[n++]=ch;
            while(j<l)
            {
                if(s[j]==ch)
                    c++;
                j++;
            }
            if(ch==' ')
                cout<<"\nFrequency of character (space) is"<<c; 
            else
                cout<<"\nFrequency of character "<<ch<<" is"<<c;
        }

    }
}

while循环中字符串的输入连接不是单次

1 个答案:

答案 0 :(得分:4)

您必须使用chy初始化Y个字符才能进入循环。你可以这样做:

char ch='y';