新手求助:如何编写程序按数字/字母顺序输出整数或字符串?
Hey there! It's totally normal to hit this roadblock as a new programmer—let's figure out what's wrong with your current code and get you sorting correctly.
The Core Issue: a<b<c Doesn't Work Like You Think
In C++, expressions like a<b<c don't check if a is less than b AND b is less than c. Instead, it evaluates left to right:
- First, it calculates
a<b, which returns a boolean value (truebecomes 1,falsebecomes 0) - Then it compares that 0/1 value to
c - This leads to totally incorrect logic (e.g.,
1<3<2would evaluate totrue<2→1<2→true, so your code would output1,3,2even though 3 isn't less than 2)
Fix 1: Correct If-Else Logic (Manual Sorting)
To properly check each possible order, you need to use logical AND (&&) to combine conditions, and use else if to ensure only one block runs. Here's how to rewrite your integer sorting code:
#include <iostream> #include <string> using namespace std; int main() { cout << "Enter three whole numbers" << endl; int a,b,c; cin >> a >> b >> c; if (a <= b && b <= c) { cout << a << "," << b << "," << c << endl; } else if (a <= c && c <= b) { cout << a << "," << c << "," << b << endl; } else if (b <= a && a <= c) { cout << b << "," << a << "," << c << endl; } else if (b <= c && c <= a) { cout << b << "," << c << "," << a << endl; } else if (c <= a && a <= b) { cout << c << "," << a << "," << b << endl; } else { // c <= b && b <= a cout << c << "," << b << "," << a << endl; } return 0; }
Fix 2: Use the Standard Sort Function (Simpler!)
For a cleaner approach (especially if you might sort more than 3 items later), you can put your values into an array and use the sort function from the <algorithm> library. This works for both integers and strings!
Integer Version:
#include <iostream> #include <algorithm> // Required for sort() using namespace std; int main() { cout << "Enter three whole numbers" << endl; int nums[3]; cin >> nums[0] >> nums[1] >> nums[2]; sort(nums, nums + 3); // Sorts the array in ascending order cout << nums[0] << "," << nums[1] << "," << nums[2] << endl; return 0; }
String Version:
If you want to sort strings instead, just swap the type to string—the logic is identical because C++ lets you compare strings with < directly:
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { cout << "Enter three strings" << endl; string strs[3]; cin >> strs[0] >> strs[1] >> strs[2]; sort(strs, strs + 3); cout << strs[0] << "," << strs[1] << "," << strs[2] << endl; return 0; }
Key Takeaways
- Always use
&&when you need to check multiple conditions (like "a is less than b AND b is less than c") - The standard
sortfunction is a huge time-saver once you understand it—no need to write all those if-else blocks! - String comparison in C++ works just like numeric comparison with
<, so sorting strings uses the same logic.
内容的提问来源于stack exchange,提问作者Sebastian Blake

