请用户输入3个国名,编程实现按字母顺序输出排在最前面的国家名。用c++字符串怎么写
时间: 2024-05-04 13:19:36 浏览: 10
可以使用 C++ 中的 `sort` 函数和 `<algorithm>` 头文件来实现按字母顺序排序。具体实现代码如下:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string country1, country2, country3;
// 从用户输入中获取3个国家名
cout << "请输入3个国家名,以空格分隔:" << endl;
cin >> country1 >> country2 >> country3;
// 使用sort函数按字母顺序排序
sort(country1.begin(), country1.end());
sort(country2.begin(), country2.end());
sort(country3.begin(), country3.end());
// 输出排在最前面的国家名
cout << "按字母顺序排序后,排在最前面的国家名是:" << endl;
if (country1 < country2 && country1 < country3) {
cout << country1 << endl;
} else if (country2 < country1 && country2 < country3) {
cout << country2 << endl;
} else {
cout << country3 << endl;
}
return 0;
}
```
在上面的代码中,我们使用了 `sort` 函数对每个输入的国家名进行排序,然后使用比较运算符 `<` 来判断哪个国家名排在最前面。注意,我们使用 `string` 类型来存储国家名,并且我们需要使用 `begin()` 和 `end()` 方法来获取字符串的首尾迭代器,以便于 `sort` 函数进行排序。