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;
}

Dani AI

Generated

Diagnosis: the behavior is caused by incorrect swap logic plus use of uninitialized temporaries. 's compiler warning is the giveaway — the code stores into the temp variables in the wrong order and never initializes them, so one value gets overwritten and the third word disappears. 's comment about certain input orders triggering the bug is exactly what happens with that swap sequence.

Two straightforward, less-error-prone approaches follow. First, avoid keeping parallel length variables and sort the strings directly (recommended). Second, if keeping manual swaps, always use a proper temp or std::swap and keep the string and its length consistent.

A compact, modern solution that sorts by length:

#include <iostream>
#include <array>
#include <algorithm>
#include <string>

int main() {
    std::array<std::string,3> w;
    std::cin >> w[0] >> w[1] >> w[2];
    std::stable_sort(w.begin(), w.end(),
        [](const std::string& a, const std::string& b){ return a.size() < b.size(); });
    for (const auto& s : w) std::cout << s << ' ';
}

Notes and troubleshooting tips:

  • Use compiler warnings (g++ -Wall -Wextra) to catch uninitialized variables early; that’s what pointed to.
  • Prefer std::swap or std::stable_sort to eliminate manual-assignment mistakes.
  • If input may contain spaces, read lines with std::getline instead of operator>>.
  • If equal-length stability matters, use stable_sort so relative order of equal-length words is preserved.

Both @ _r0ckbaer’s sort idea and ’s minimal-swap outline are valid; using the standard library keeps the code shorter and far less fragile than maintaining parallel length variables and homemade swap sequences.

Recommended Answers

All 4 Replies

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.