-5

I am looking to check if two string are permutations of each other. I am using the following code :

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

void sort(char *str)
{
    char temp;
    for(int i=0;i<strlen(str);i++)
    {
        if(str[i]>str[i+1])
        {
            temp=str[i];
            str[i]=str[i+1];
            str[i+1]=temp;
        }
    }
}

int main()
{
    char string1[10],string2[10];
    int val;
    cout<<"Enter first string";
    gets(string1);
    cout<<"Enter second string";
    gets(string2);
    val = strcmp(sort(string1),sort(string2));
    if(val==0)
    {
        cout<<"Same strings"<<endl;
    }
    else 
    {
        cout<<"Different Strings"<<endl;
    }
    return 0;
}

But I am getting a "invalid use of void expression error" at the strcmp line. How do I fix this ? Thanks

Shivam Bhalla
  • 1,879
  • 5
  • 35
  • 63

3 Answers3

2

It looks like you want to compare strings after sorting. Assuming your sort function does the right thing, you need to compare the strings after sorting them.

sort(string1);
sort(string2);
val = strcmp(string1, string2);

The reason for the error is that your sort function returns void. So you are effectively passing void arguments to strcmp. And that can't work.

The way to do this in C++ would be to use std::string, and call std::sort.

std::string string1, string2;
std::cout << "Enter first string";
std::cin >> string1;
std::cout << "Enter second string";
std::cin >> string2;
std::sort(string1.begin(), string1.end());
std::sort(string2.begin(), string2.end());
bool val = string1 == string2;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Except there's already an algorithm for this (in C++11 at least): `std::is_permutation` :) It's even better in C++14 since you don't need to worry about different lengths. – chris Jul 15 '14 at 16:23
  • Yes I am aware of that function :). I am looking to implement it manually though. But I seem to get "different string" displayed each time. Any idea why ? – Shivam Bhalla Jul 15 '14 at 16:48
0

sort returns nothing (void), so its return value cannot serve as parameter to strcmp.

sort(string1);
sort(string2);
val = strcmp(string1, string2);
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
  • Thanks! That did the trick. However, there is apparently a logical problem here as I am still getting a "different strings" even if i put same strings as input. Why is that ? – Shivam Bhalla Jul 15 '14 at 16:15
0

You can't strcmp the void returns from sort(). You want to sort() first and then strcmp the sorted strings, something like:

sort(string1);
sort(string2);
val = strcmp(string1, string2);
Paul Evans
  • 27,315
  • 3
  • 37
  • 54