这样都错了,求解答解决方法
这样都错了,求解答
#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];
------解决方案--------------------
#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;
}