21xrx.com
2025-03-24 16:56:25 Monday
文章检索 我的文章 写文章
C++输入3个字符串,按照由小到大的顺序输出
2023-06-25 21:51:43 深夜i     55     0
C++ 输入 字符串 小到大 输出

C++是一种高级程序设计语言,具有强大的编程能力。在C++编程中,处理字符串是一项很常见的任务。本文将介绍如何输入3个字符串,并按照由小到大的顺序输出。

首先,使用C++中的字符串类型来定义3个字符串变量,可以使用std命名空间,如下所示:

#include <iostream>
#include <string>
using namespace std;
int main()
str2

接着,通过使用C++中的判断语句和字符串比较函数,按照由小到大的顺序输出这三个字符串。可以使用if-else语句,按照字符串的大小关系进行判断。最终,使用cout输出3个字符串的顺序。具体代码如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1, str2, str3;
  cout << "请输入3个字符串:" << endl;
  cin >> str1 >> str2 >> str3;
  if (str1 < str2 && str1 < str3)
  {
    cout << str1 << " ";
    if (str2 < str3)
    
      cout << str2 << " " << str3 << endl;
    
    else
    
      cout << str3 << " " << str2 << endl;
    
  }
  else if (str2 < str1 && str2 < str3)
  {
    cout << str2 << " ";
    if (str1 < str3)
    
      cout << str1 << " " << str3 << endl;
    
    else
    
      cout << str3 << " " << str1 << endl;
    
  }
  else
  {
    cout << str3 << " ";
    if (str1 < str2)
    
      cout << str1 << " " << str2 << endl;
    
    else
    
      cout << str2 << " " << str1 << endl;
    
  }
  return 0;
}

在以上代码中,首先输入3个字符串,然后使用if-else语句判断它们之间的大小关系,最后按照由小到大的顺序输出这3个字符串。

以上就是C++中输入3个字符串,按照由小到大的顺序输出的方法。需要注意的是,这种方法仅适用于3个字符串的情况,如果有更多的字符串需要排序,那么就需要使用其他的排序算法来对字符串进行排序。

  
  

评论区