C++比较两个字符串
这个C++程序比较两个输入的字符串大小。程序使用string类的compare()方法比较str和str2,若返回值为0则输出相等,大于0输出str较大,小于0输出str较小。测试输入"ABCD XYZ"时,程序会输出"ABCD is less than XYZ",因为按字典序ABCD小于XYZ。程序简洁地实现了字符串比较功能,适合初学者理解基本字符串操作。
输入
ABCD XYZ
输出
ABCD is less than XYZ
#include<bits/stdc++.h>
using namespace std;
int main(){string str,str2;cin>>str>>str2;int n=str.compare(str2);if(n==0){cout<<str<<" is equal to"<<str2;}else{if(n>0){cout<<str<<" is greater than "<<str2;}else{cout<<str<<" is less than "<<str2;}}return 0;
}