Group
Advanced Conditional Structures in C++
Objective
1. Prompt the user to input two strings.
2. Convert both strings to lowercase to ensure case-insensitive comparison.
3. Sort the characters in both strings alphabetically.
4. Compare the sorted strings.
5. Display whether the two strings are anagrams or not.
Create a program that determines if a given pair of strings are anagrams.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input/output stream library
#include <algorithm> // Include algorithm library for sort and transform
#include <string> // Include string library
using namespace std;
bool areAnagrams(string str1, string str2) {
// Convert both strings to lowercase
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
// Sort both strings
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Compare sorted strings
return str1 == str2;
}
int main() {
string word1, word2; // Variables to store user input
// Prompt the user for the first word
cout << "Enter the first word: ";
cin >> word1;
// Prompt the user for the second word
cout << "Enter the second word: ";
cin >> word2;
// Check if the words are anagrams
if (areAnagrams(word1, word2)) {
cout << "The words are anagrams." << endl;
} else {
cout << "The words are not anagrams." << endl;
}
return 0; // End of program
}
Output
Enter the first word: listen
Enter the second word: silent
The words are anagrams.