#include<iostream>
#include<string>
using namespace std;
int main()
{
int i; //i为测试数据组数
string s1,s2; //s1,s2存储字符
int len1,len2; //len1,len2分别为对应长度
cin>>i;
while(i--)
{
cin>>s1;
cin>>s2;
len1=strlen(s1);
len2=strlen(s2);
if(len1>len2)
cout<<s1<<" is longer than "<<s2<<endl;
else if(len1<len2)
cout<<s2<<" is longer than "<<s1<<endl;
else
cout<<s1<<" is equal long to "<<s2<<endl;
}
return 0;
}
以上代码有问题。string a;这样是不对的,因strlen是对char类型的来说的,应该定义成char a[100];以下代码是正确的。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i; //i为测试数据组数
char s1[100],s2[100]; //s1,s2存储字符
int len1,len2; //len1,len2分别为对应长度
cin>>i;
while(i--)
{
cin>>s1;
cin>>s2;
len1=strlen(s1);
len2=strlen(s2);
if(len1>len2)
cout<<s1<<" is longer than "<<s2<<endl;
else if(len1<len2)
cout<<s2<<" is longer than "<<s1<<endl;
else
cout<<s1<<" is equal long to "<<s2<<endl;
}
return 0;
}
还有一种不错的方法,用string s1,s2;定义,调用s1、s2的length方法。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i; //i为测试数据组数
string s1,s2; //s1,s2存储字符
int len1,len2; //len1,len2分别为对应长度
cin>>i;
while(i--)
{
cin>>s1;
cin>>s2;
len1=s1.length();
len2=s2.length();
if(len1>len2)
cout<<s1<<" is longer than "<<s2<<endl;
else if(len1<len2)
cout<<s2<<" is longer than "<<s1<<endl;
else
cout<<s1<<" is equal long to "<<s2<<endl;
}
return 0;
}