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