读书人

这样都错了求解答解决方法

发布时间: 2012-05-06 16:15:43 作者: rapoo

这样都错了,求解答
#include<iostream>
using namespace std;
int main()
{
const int N=80;
char buffer[N];
int k=0;
const int NUM=26;
int counts[NUM]={0};
char letters{NUM};
int i=0;
do
{
cout<<"Enter a string:"<<endl;
cin.getline(buffer,N,'\n');
k=0;
while(buffer[k]!='\n')
{
i=tolower(buffer[k]-'a');
counts[i]++;
k++;
}
}while(buffer[0]!='\n');
cout<<"The statistic result is:"<<endl;
for(i=0;i<NUM;i++)
{
letters[i]=(char)('a'+i); //1)
if(counts[i]>0)
{
cout<<letters[i]<<":"<<counts[i]<<endl; //2)

}
}
return 0;
}


显示的error:
1)invalid types 'char[int]' for arry subcript
2) invalid types for arry subcript


[解决办法]
char letters{NUM}; char letters[NUM];
[解决办法]

C/C++ code
  const int NUM=26;  int counts[NUM]={0};  char letters{NUM};//楼主你这儿错了,应该是[]
[解决办法]
数组越界 比如counts[i]++; 这个i可能大于26 也可能小于0
[解决办法]
修改后的:
#include<iostream>
using namespace std;
int main()
{
const int N=80;
char buffer[N];
int k=0;
const int NUM=26;
int counts[NUM]={0};
char letters[NUM] = {0};
int i=0;
do
{
cout<<"Enter a string:"<<endl;
cin.getline(buffer, N, '\n');
k=0;

while(buffer[k] != 0)
{
i = tolower(buffer[k])-'a';
counts[i] += 1;
k++;
}
}while(buffer[0]!=0);
cout<<"The statistic result is:"<<endl;
for(i=0;i<NUM;i++)
{
letters[i]=(char)('a'+i); //1)
if(counts[i]>0)
{
cout<<letters[i]<<":"<<counts[i]<<endl; //2)

}
}
return 0;
}
[解决办法]
C/C++ code
while(buffer[k]!='\n')        {            i=tolower(buffer[k]-'a');            counts[i]++;            k++;        }
[解决办法]
#include<iostream>
using namespace std;
int main()
{
const int N=80;
char buffer[N];
int k=0;
const int NUM=26;
int counts[NUM]={0};
char letters[NUM];
int i=0;
do
{
cout<<"Enter a string:"<<endl;
cin.getline(buffer,N,'\n');
k=0;
while(buffer[k]!='\n')
{
i=tolower(buffer[k]-'a');
counts[i]++;
k++;
}
}while(buffer[0]!='\n');
cout<<"The statistic result is:"<<endl;
for(i=0;i<NUM;i++)
{
letters[i]=(char)('a'+i); //1)
if(counts[i]>0)
{
cout<<letters[i]<<":"<<counts[i]<<endl; //2)

}
}
return 0;
}

读书人网 >C++

热点推荐