Hi guy, I need to create a program that sorts 3 words entered into order from shortest to longest. So far I have the following done but when I run it, it only displays the first two words in order of length and doesnt show the 3rd word. Can anyone tell me what is wrong with it?

#include<iostream>
#include<string>

using namespace std;
int main()
{
    int num1,num2,num3,ntemp, count = 0;
    string name1,name2,name3,stemp;
    
    cout << "enter 3 words.\n";
    cin >> name1 >> name2 >> name3;
    num1 = name1.length();
    num2 = name2.length();
    num3 = name3.length();
    
    while (count <= 1)
    {
    if (num1 > num2)
    {
             num1 = ntemp;
             num1 = num2;
             num2 = ntemp;
             
             name1 = stemp;
             name1 = name2;
             name2 = stemp;
    }
    
    if ( num2 > num3 )
    {
             num2 = ntemp;
             num2 = num3;
             num3 = ntemp;
             
             name2 = stemp;
             name2 = name3;
             name3 = stemp;
    }
     
    count++;
    }   
    cout << name1 << " " << name2 << " " << name3 << " ";
    
    system("pause");
    return 0;
}

Here's a hint

g++ -W -Wall -ansi -pedantic -O2 foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:20: warning: ‘ntemp’ is used uninitialized in this function

Fix the order of assignments to actually swap two variables.

try this solution:

bool SortBylength(const string& a, const string& b)
{
	if (b.length() > a.length())
	{
		return true;
	}

	return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<string> v;

	for (int i = 0; i < 3; i++)
	{
		cout << "enter word " << i + 1 << ": ";
		string word;
		getline(cin, word);
		v.push_back(word);
	}
   
	sort(v.begin(), v.end(), SortBylength);

	cout << "sorted words by length: ";
	copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
	cout << endl;
	system("Pause");

	return 0;
}

Think
According to your code what will happen in foll condition
if the first word entered is second largest second is largest and third one is smallest.....

//find the smallest of the three
if second less than first
  swap first and second
if third less than first
  swap first and third

//find the smallest of the remaining two
if third less than second
  swap second and third

//first is now smallest, with third largest and second in between
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.