How to compare four C++ strings and sort them by length

CWC
2 Min Read

A program that reads four strings from the standard input and outputs them in descending order in the standard output depending on their length.

Below is the small C++ program source code to compare four C++ strings and sort them by length:
[sociallocker]

#include 
#include 

using namespace std;

int main()
{
   
   const string s1 = "Taco";
   const string s2 = "Flautas";
   const string s3 = "Taco Salad with Chicken";
   const string s4 = "Burrito";
   
   string out1;
   string out2;
   string out3;
   string out4; 
   
   // copy all strings into the temporary out variables
   out1 = s1; out2 = s2; out3 = s3; out4 = s4;

   // We'll bubble sort these strings.
   bool strings_are_sorted = false;
   while (!strings_are_sorted)
   {
    strings_are_sorted = true;
       if (out1 > out2)
       {
       strings_are_sorted = false;
        swap(out1, out2);  // Or write your own swap code
      continue;
      }
      if (out2 > out3)
      {
      strings_are_sorted = false;
      swap(out2, out3);  // Or write your own swap code
      continue;
      }
      if (out3 > out4)
      {
      strings_are_sorted = false;
      swap(out3, out4);  // Or write your own swap code
      continue;
      }
   }
   cout << out1 << "\n" << out2 << "\n" << out3 << "\n" << out4 << endl;
   return 0;
}

[/sociallocker]

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version