Search code examples
c++functionanagram

Logical Issue or Syntax issue with sorting String function


I'm new to C++ and coding in general. I'm attempting to make a simple program that essentially takes in two words and will tell you if these two words are anagrams or not.I also understand that there is likely a pre-made function to sort a string, like an array however I am trying to grasp the concept itself and hence why I'm attempting to make the function.

Here is a quick snippet of the code I've written so far.

Snippet of code

The issue that I'm currently having is that when I call the function to sort the string, the string isn't sorted! Sorry if there is a simple solution to this, I'm fairly new. Is this a logical issue or syntax based? Thank you so much!


#include <iostream>
#include <string>
using namespace std;

//Function Declarations
string sortString(string user_input);

//Program Body
int main()
{
    string user_input_one, user_input_two;
    cout << "Welcome to Sandip's Anagram Checker! \nPlease Input two words that you'd like the check!";
    sortString(user_input_one);
    sortString(user_input_two);
    if (user_input_one == user_input_two)
        cout << "These two words are Anagrams of each other!";
    else
        cout << "These are not Anagrams!";
    return 0;
}

//Function Definations
string sortString(string user_input)
{
    string temp_string = user_input;
    int i,j;
    for (i = 0; i<user_input.length();i++)
    {
        for (j=0; j<user_input.length();j++)
        {
            if (user_input[i] == user_input[j])
            {
                temp_string[i] = user_input[j];
            }
            else if (user_input[i] > user_input[j])
            {
                temp_string[i] = user_input[j];
            }
            else if (user_input[i] < user_input[j])
            {
                temp_string[i] = user_input[i];
            }

        }
    }
    return temp_string;
}


Solution

  • Adding to Daniel's answer, you don't need a temporary string in the sorting function, just process the passed string and return it. Also consider supporting letter cases as well, you can use std::transform from the STL algorithm library.

    #include <algorithm>
    

    Add this before looping in your sorting function or after taking inputs in main.

    transform(user_input.begin(), user_input.end(), user_input.begin(), ::tolower);