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

C++的string 类到底要怎么用? 出现strcmp 2664错误 要怎么解?

wingc 发布于 2020-03-10 22:19, 1801 次点击
我自己写的代码,但不会解这个错误,求大神帮忙,谢谢啦!

#include<iostream>
#include<string>
using namespace std;
void main()     //找出输入到数组A中的最长和最短的字符串,并求平均长度且A要动态申请空间并最后释放。
{ int n,i,j,max,min,sum=0,avg;
string *A;
cout<<"输入一个整数n:"<<endl;
cin>>n;
A=new string[n];    //题目要求要动态分配空间
cout<<"输入"<<n<<"个字符串"<<endl;
for(i=0;i<n;i++)
cin>>A[i];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{ if(strcmp(A[i],A[j])>0)
       max=i;  //记录下最长串的数组下标
  else min=i;  //记录下最短串的数组下标
}
cout<<"最长的串为:"<<A[max]<<"\n最短的串为:"<<A[min]<<endl;
cout<<"n个字符串的平均长度为:"<<(sizeof(A)-n)/n<<endl;  //这个我也不知道算法对不对
delete []A;  //释放空间
}
5 回复
#2
gzy4442020-03-10 23:10
应该是strcmp函数只能比较char值,其他的好像都不行
#3
rjsp2020-03-11 09:06
题目让你“最和最的字符串”,你用 strcmp 是想求最的字符串?
(sizeof(A)-n)/n ------ 这个 sizeof(A) 又是什么?

程序代码:
#include <iostream>
#include <string>
using namespace std;

int main( void )
{
    size_t n;
    cin >> n;

    string* a = new string[n];
    {
        size_t longest_idx = 0;
        size_t shortest_idx = 0;
        size_t sum_length = 0;
        for( size_t i=0; i!=n; ++i )
        {
            cin >> a[i];

            if( a[longest_idx].size() < a[i].size() )
                longest_idx = i;

            if( a[shortest_idx].size() > a[i].size() )
                shortest_idx = i;

            sum_length += a[i].size();
        }
        cout << "the longest string is: " << a[longest_idx] << '\n';
        cout << "the shortest string is: " << a[shortest_idx] << '\n';
        cout << "the average length is: " << sum_length*1.0/n << '\n';
    }
    delete[] a;

    return 0;
}

输入
3
abc
abcdefghijk
abcdef
输出
the longest string is: abcdefghijk
the shortest string is: abc
the average length is: 6.66667

#4
xianfajushi2020-03-11 09:25
通过转换试看还有错误提示?

                if (strcmp((char*)&A[i], (char*)&A[j])>0)
#5
rjsp2020-03-11 10:00
以下是引用xianfajushi在2020-3-11 09:25:28的发言:

通过转换试看还有错误提示?
 
                if (strcmp((char*)&A, (char*)&A[j])>0)

如果是比较大小,std::string 可直接使用 operator >,也就是 if(strcmp(A[i],A[j])>0) 改为 if( A[i] > A[j] )
如果一定要用 strcmp,那应该是 if( strcmp(A[i].c_str(),A[j].c_str()) > 0 )
#6
xianfajushi2020-03-11 14:53

strlen(A[0].data())
1