[英]cin.getline() not working inside a while loop
這是我在多行字符串中查找字符頻率的程序:
#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循環內的字符串輸入甚至一次都沒有
您必須使用y
或Y
初始化您的ch
字符才能進入您的循環。 你可以簡單地這樣做:
char ch='y';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.