Question

Anagram finding function

Asked by: weinrj

Hi...I know this is for school...this is what I have so far.  the idea of the program is to use two strings.  string one the user inputs a word and the next string an anagram of that word, ie., string 1: dear, string 2: dare

and naturally output if is passes or not.

this is a beginner's course below is what i have as of now.

thanks!

(i need help in figuring out how do i figure out if it is an anagram??!!)


#include <iostream.h>
#include <ctype.h>

bool anagram(char [], char []);

int main() {
      cout << "Welcome to Anagram Detector!\n\n>> ";
      char ch, array1[256], array2[256];
      int i = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array1[i] = ch;
            i++;
      } while (ch != '\n');
    array1[i] = '\0';

      cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
      int j = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array2[j] = ch;
            j++;
      } while (ch != '\n');
    array2[j] = '\0';

// make an if to call function??

      return 0;
}

bool anagram(char test1[], char test2) {

// i know this does absolutly nothing
return true;
}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
1999-12-09 at 08:42:15ID10244836
Tags

anagram

Topic

C++ Programming Language

Participating Experts
5
Points
100
Comments
74

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Colors with cout
    I'm wondering if there is a way to give a string a color with cout? I know how to do with cprintf but not with cout.
  2. (CString) BOOL
    Hi Is there an esy way to convert a BOOL to a string, like "1" = TRUE, "0" = FALSE CB.
  3. I need help with an anagram array program.
    I am writing an anagram checker program and am having difficulty trying to check if a word pair is an anagram. I am using two parallel arrays and two strings and think I need to use a "for" loop, but I am getting confused and would appreciate help!
  4. Anagram program
    How do you write an anagram program where the user enters two words, and the response tells if the second word is an anagram of the first word?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: GleasonGuyPosted on 1999-12-09 at 09:37:50ID: 2269299

What exactly are you having problems with? Getting the strings or comparing them?

If it is comparing them, I think I would strip out the whitespace, sort the characters in each string and then compare the results. If they are equal, then you have an anagram.

 

by: weinrjPosted on 1999-12-09 at 09:55:30ID: 2269356

oh damn i put getline...ooops

ok...how do i compare them is what i wanted to ask in that bool function?

 

by: weinrjPosted on 1999-12-09 at 09:57:12ID: 2269360

wait
i did that for the \n

how do i get rid of whitespace?

 

by: GleasonGuyPosted on 1999-12-09 at 10:12:01ID: 2269406

There are often many ways to do what you want. I'm not sure what is required by your class.

To detect whitespace, you can use isspace(). You can use isspace to determine wheter to copy a character from your original string or not.

To compare two character array you can use strcmp().

 

by: weinrjPosted on 1999-12-09 at 10:35:00ID: 2269473

ok but when comparing will dear and dare be same? or dare and dare?

requirements are minimal, just to use tolower, and detect if anagram in function.  ( i like bool so i am doing this )

this program can be complex as i want it to be...

i will attempt to do this

pseudo code

compare string1 and string2 using function

function

if true then return true
if false,then return false

print out accordingly

 

by: GleasonGuyPosted on 1999-12-09 at 10:47:30ID: 2269507

Your general pseudo code looks code.
Now you should post some for your compare function and I'll let you know what your missing.

 

by: weinrjPosted on 1999-12-09 at 11:02:48ID: 2269559

this is what i cant think of how i am going to do this

i think i need a counter
and thats about it

 

by: GleasonGuyPosted on 1999-12-09 at 11:10:08ID: 2269580

I think I would try the following...

- Compare string1 and string2
- return 1 if they are identical
- copy string1 to temp1 discarding whitespace and converting to lowercase
- copy string2 to temp2 discarding whitespace and converting to lowercase
- sort the characters in temp1
- sort the characters in temp2
- if length of temp1 != length temp2, return 2
- compare temp1 and temp2
- return 0 if they are identical
- return 2 if they are not.

dear, dare would return 0
dare, dare would return 1
dear, deer would return 2

 

by: weinrjPosted on 1999-12-09 at 12:46:27ID: 2269817

ah have a true, and false and equals...but i would like to use a bool functions (to show off)

 

by: GleasonGuyPosted on 1999-12-09 at 13:02:07ID: 2269860

Sure you can return a bool. It's your function you can do wahtever you want.
I think it would be more robust to return multiple values. After you've looked at the prototype for a lot of compare functions, like you are writing, 0 is usually success and non-zero is an error code.

If you look at the strcmp() function it returns -1 for a<b, +1 for a>b, and 0 for a==b. This is the kind of thing I was suggesting.

As for using boolean expressions you can say !function() means success.

But you shouldn't worry so myuch about the return value. Try coding up the function and getting it to work. Use the debugger or print commands to check your algorithm.

Good luck.

 

by: weinrjPosted on 1999-12-09 at 13:06:54ID: 2269867

yes i agree it will be more robust...but it just wants a yes or no, so bool seemed logical.  if it does the minimum u get the A, if u go all the way, he doesnt do anything extra special.  

I got work later tonight so I will work on this tomorrow.  I believe the due date is 20 Dec.

 

by: andlaPosted on 1999-12-09 at 13:16:56ID: 2269893

This is a samplecode that i found on an anagram. It must have like all the angrams a dictionary to find words. I you compile and run this program you can use:
anagram.exe -dDictionary.txt -oOutputfile.txt Mystring

if you have a file named Dictionary.txt
and wants the output to file Outputfile.txt and test the work 'Mystring' without "" or ''

http://www.brevard.cc.fl.us/wbcc/staff/harry/cprogs/anagram11.c

I hope this helps. :-)

 

by: andlaPosted on 1999-12-09 at 13:19:09ID: 2269904

I found this to but i could not compile the sample.

http://www-cse.ucsd.edu/~calder/classes/spring99/cse231/course_work.html

 

by: weinrjPosted on 1999-12-09 at 13:44:06ID: 2269979

way too complex....

 

by: andlaPosted on 1999-12-09 at 14:41:35ID: 2270182

Everthing looks complex at the first sight. Please explain what i can do for you? What kind of tools (functions, classes) do you want?

 

by: weinrjPosted on 1999-12-09 at 18:43:08ID: 2270611

just one function (not including main)

everything is done in main
function just determines if it is an anagram or not.

by the true or false return, it will display output accordingly

 

by: andlaPosted on 1999-12-10 at 03:58:17ID: 2271437

So if i create a function that for example a user put in value for example millenum and it found these:
Immune i'll
Immune ill
I'll menu i'm
I'll 'em i'm unMenu mill i
Menu i'm ill
Mien mull i
Mill 'em un i
Mill me un i
Mine mull i
Mule i'm nil
Mull 'em in i
Mull in me i
Null 'em i'm i
Null i'm me i
I'll i'm me un

'em i'm ill un
Ell mum in i
I'm ill me un
Lie mum nil

it will return TRUE witch is the string of all hits.
If no hits where found it will return FALSE

 

by: GleasonGuyPosted on 1999-12-10 at 07:29:00ID: 2271685

andla, weinrj is not looking for a function to CREATE an anagram. He is looking for a function to COMPARE two strings and determine if they are anagrams of each other.

This is a homework/lab problem, so please do not post the function for weinrj. I have given him pseudo code for the function already (which in hindsight was probably too much).

weinrj, I think that you should be able to get the function coded without too much difficulty. Once you have it coded, post any specific questions and we can help you out.

 

by: andlaPosted on 1999-12-10 at 07:34:19ID: 2271713

GleasonGuy->"
This is a homework/lab problem, so please do not post the function for weinrj. "

You must be the school-teacher ? "joke" :-)

I suppose i can help how to build the function.

 

by: GleasonGuyPosted on 1999-12-10 at 07:47:08ID: 2271761

No, I'm not a teacher. It is grounds to be kicked off Experts Exchage to post homework solutions for people. It is OK to answer specific questions or to help with concepts. It is NOT OK to do the work for the person.

The point of homework and labs is to turn the student into an Expert in their own right.

As I said, I've already provided pseudo code. Let weinrj give it a shot.

 

by: andlaPosted on 1999-12-10 at 08:18:06ID: 2271878

GG>> I read the agreement and nowhere i read about that you said. I agree with you that not to help cheeting in the homework. I don't agree with you that people that are in trouble can't get any help because that would be to do all the work for that person. I read that i can't using usernames without permission so for that i'm sorry. I will use initials instead.

 

by: TallBoyPosted on 1999-12-10 at 13:59:21ID: 2272759

Weinrj,

As someone pointed out, the easiest way for you to do it is to sort the two strings, then compare them.  If they are identical, then they are anagrams.

For sorting, I usually use the QuickSort algorithm.  My example here was compiled under MSVC++ 6.0.

------------------

void CSDlg::QuickSort( CString strList[], int low, int high )
{
      /**************************************************
      ** strList = Array of Cstrings                   **
      ** l       = Low boundary of array (usually 0)   **
      ** r       = High boundary of array              **
      **                                                                       **
      ** All Strings are temporarily converted to      **
      ** lower case for the sort.                      **
      **                                                                       **
      ** Adapted from code at:                                   **
      **  http://www.cs.jcu.edu.au/ftp/web/teaching/   **
      **  Subjects/cc1002/1997/notes/lect17/qsort.html **
      **************************************************/

      CString pivot;
      int left, right;
      
      left = low; right = high;
      pivot = _strlwr( _strdup( strList[ (left + right) / 2 ] ) );
      while (right >= left)
      {
            // find the next elements on the wrong
            // sides of the pivot and swap them
            while ( _strlwr( _strdup( strList[right] ) ) > pivot) right--;
            while ( _strlwr( _strdup( strList[left] ) )  < pivot) left++;
            if( left <= right )
            {
                  swap( strList, left, right  );
                  left++;   right--;
            }
      }

      // recursively sort the lower and upper
      // parts of the array
      if (low < right) QuickSort(strList, low, right);
      if (left < high) QuickSort(strList, left, high);

}

----------------

Note that I use CStrings, but the algorithm will still work with chars.

Next, you do a compare, so I'd use

if( strcmp(str1, str2)==0 )
  cout << "Anagram!\n";
else
  cout << "Not an anagram.\n";

If you're still using CStrings, then you can just use

if( str1 == str2 )
 ...

and so on, and you're done.

-:-

Now, if you want to make the thing check for complex anagrams, such as those that are multiple words, then you're going to have to strip out the spaces.

To do this, there are several different ways.

1) Using CStrings (this is one reason why I love 'em!), you can use TrimLeft(str) or TrimRight(str).
2) For chars, you're going to have to do a bit more work:

/* assume str is the string to strip */
char* temp;
int i;
for( i = 0; i < strlen( str ); i++ )
{
  /* Append to temp if not a space */
  if( str[i] != ' ' )
    strcat( temp, str[i] );
}

/* make temp end with a null, for safety */
strcat( temp, '\0' );

....

Now your temp variable contains what str did without all the spaces.  You compare it as above.

Good luck!

 

by: weinrjPosted on 1999-12-10 at 14:21:15ID: 2272817

i will keep this locked as u gave me a lot of complex info.

i will see how i handle this over the weekend.

 

by: andlaPosted on 1999-12-10 at 14:24:34ID: 2272832

Just ask and we will answer. :-)

 

by: weinrjPosted on 1999-12-11 at 09:56:55ID: 2274099

i agree that a sort would be best but you gave me code.  i dont understand it!

so what i want to do is sort string1 and string2

then i will do a string compare

i get that part -- how do i sort the text??  quick sort may be too complex for me.  what about bubble or insertion?  thanx

 

by: GleasonGuyPosted on 1999-12-11 at 10:10:58ID: 2274114

A bubble sort on each string would do just fine for you.

You want it so that "dare" would become "rdea" (or "aedr" depending on the direction you sort).

 

by: ozoPosted on 1999-12-11 at 10:17:44ID: 2274131

#include <stdlib.h>
void qsort (void* base, size_t nmemb, size_t size, int (*compar) (const void *, const void *));

 

by: weinrjPosted on 1999-12-11 at 10:26:25ID: 2274142

why wouldnt it be ader?  i am making the letter fully in alphabetical order right?  so dare become ader
and read become ader so when i do a compare they are equal thus an anagram.  right?
how do i sort chars in a bubble?  man i didnt do sorts in awhile, back to the text book!

 

by: weinrjPosted on 1999-12-11 at 10:35:29ID: 2274160

thus far is this
let me know before i go on

#include <iostream.h>
#include <ctype.h>
#include <string.h>

bool anagram(char [], char []);

int main() {
      cout << "Welcome to Anagram Detector!\n\n>> ";
      char ch, array1[256], array2[256];
      int i = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array1[i] = ch;
            i++;
      } while (ch != '\n');
    array1[i] = '\0';

      cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
      int j = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array2[j] = ch;
            j++;
      } while (ch != '\n');
    array2[j] = '\0';


      return 0;
}

bool anagram(char test1[], char test2[]) {

// Sort both algorithms
      // Compare algorithms

      int i, hold;

      for ( int pass = 0; pass < strlen(test1) - 1; pass++ )
            for ( i = 0; i < strlen(test1) - 1; i++ )
                  if (test1[i] > test1[i + 1]){
                        hold = test1[i];
                        test1[i] = test1[i+1];
                        test1[i+1]=hold;
                  }

            cout << "Gore: ";
            for ( i = 0; i < strlen(test1); i++ )
                  cout << setw(3) << test1[i];



return true;
}
   





 

by: weinrjPosted on 1999-12-11 at 10:42:33ID: 2274165

this code is better...i havent compiled it yet, but this is what i got so far...i commented a line towards the bottom .  thnx

#include <iostream.h>
#include <ctype.h>
#include <string.h>

bool anagram(char [], char []);

int main() {
      cout << "Welcome to Anagram Detector!\n\n>> ";
      char ch, array1[256], array2[256];
      int i = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array1[i] = ch;
            i++;
      } while (ch != '\n');
    array1[i] = '\0';

      cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
      int j = 0;
      do {
            cin.get(ch);
            ch = char(tolower(ch));
            array2[j] = ch;
            j++;
      } while (ch != '\n');
    array2[j] = '\0';
   
      cout << "Is this an anagram: " << anagram(array1,array2);
      // if true print YES if false, print NO

      return 0;
}

bool anagram(char test1[], char test2[]) {

// Sort both algorithms
      // Compare algorithms

      int i, hold, j, held;

      for ( int pass = 0; pass < strlen(test1) - 1; pass++ )
            for ( i = 0; i < strlen(test1) - 1; i++ )
                  if (test1[i] > test1[i + 1]){
                        hold = test1[i];
                        test1[i] = test1[i+1];
                        test1[i+1]=hold;
                  }

    for ( int pass1 = 0; pass1 < strlen(test1) - 1; pass1++ )
            for ( j = 0; j < strlen(test2) - 1; i++ )
                  if (test2[i] > test2[j + 1]){
                        held = test2[j];
                        test2[j] = test2[j+1];
                        test1[j+1]=held;
                  }

    if ( test1 == test2 )
            return true;
      else
            return false;
            
}    





 

by: GleasonGuyPosted on 1999-12-11 at 10:45:13ID: 2274168

Sorry about that... it would be "ader"... I gues my internal alphabet routtine needs some work ;-)

Your bubble sort looks OK to me. It will get the job done although it is not optimized.

Are you going under the assumption that there will be no whitespace? For example, "dare" and "read", but not "a red".

If "a red" is OK then you have to strip out whitespace before you sort.

Also, I would put your nested for loops in their own function called SortString() or something. You will need to use it twice. Once for each string.

 

by: weinrjPosted on 1999-12-11 at 10:47:02ID: 2274172

in 2nd for loop, i forgot to made tes1[j+1], its test2...but i know this is wrong since the loop algorithm is for int not chars, so i need help with that

 

by: GleasonGuyPosted on 1999-12-11 at 10:47:58ID: 2274174

It looks like it should work. Compile it and run some test cases.

For the return of anagram, you can simplify your code by putting...

return( test1 == test2);

 

by: GleasonGuyPosted on 1999-12-11 at 10:49:28ID: 2274176

That's why cut and paste is bad and functions are good.

You also are incrementing i in the second loop instead of j.

 

by: weinrjPosted on 1999-12-11 at 11:03:34ID: 2274193

i got four warnings '<' signed/unsigned mismatch

it ran but after the 2nd was inputted it froze or stopped

 

by: weinrjPosted on 1999-12-11 at 11:06:15ID: 2274196

and the output needs working on for if it is one or not

 

by: GleasonGuyPosted on 1999-12-11 at 19:28:32ID: 2274653

Can you tell where it is stopping? If not you can use the debugger to trace through your code. Or you can put cout statements in different places in your code to see if it reaches them.

FYI,
ch = char(tolower(ch));
array1[i] = ch;
i++;

can be combined to
array1[i++] = char(tolower(ch));

 

by: andlaPosted on 1999-12-12 at 05:39:29ID: 2275099

Remember that cin.get(n) leaves a new line (\n) in the buffer. Next time when the loop gets to cin.get it will not wait for you because it thinks you pressed the return key.

I tok some time to write a new code piece of the input snippet.

while(1)
{
      ch=cin.get();
      if(ch=='\n')
      break;
      cin.get();
      ch = char(tolower(ch));
      array2[j] = ch;
      j++;
}

Good luck!

 

by: weinrjPosted on 1999-12-12 at 07:21:01ID: 2275230

#include <iostream.h>
#include <ctype.h>
#include <string.h>

bool anagram(char [], char []);

int main() {
      cout << "Welcome to Anagram Detector!\n\n>> ";
      char ch, array1[256], array2[256];
      int i = 0;
      do {
            cin.get(ch);
            array1[i++] = char(tolower(ch));

      } while (ch != '\n');
    array1[i] = '\0';

      cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
      int j = 0;
      while(1)
      {
            ch=cin.get();
            if(ch=='\n')
                  break;
            cin.get();
          ch = char(tolower(ch));
            array2[j] = ch;
            j++;
}



    array2[j] = '\0';
      cout << "Is this an anagram: " << anagram(array1,array2);
      // if true print YES if false, print NO

      return 0;
}

bool anagram(char test1[], char test2[]) {



      int i, hold, j, held;

      for ( int pass = 0; pass < strlen(test1) - 1; pass++ )
            for ( i = 0; i < strlen(test1) - 1; i++ )
                  if (test1[i] > test1[i + 1]){
                        hold = test1[i];
                        test1[i] = test1[i+1];
                        test1[i+1]=hold;
                  }

    for ( int pass1 = 0; pass1 < strlen(test2) - 1; pass1++ )
            for ( j = 0; j < strlen(test2) - 1; i++ )
                  if (test2[j] > test2[j + 1]){
                        held = test2[j];
                        test2[j] = test2[j+1];
                        test2[j+1]=held;
                  }

    return (test1 == test2);
            
}    


after i input the 2nd string it supposed to check the string.

is there an error in the function?  is there an error in calling the function?

is there an error because I am not printing anything???

there should be...there is an output before the function is called...i think something is happening before the function is being called...but would this function still would with chars?? i dont see why not.

but i still get that signed / unsigned mismatch - its w/ the nested for pass for i for pass1 for j loops

man this is sure puzzling - i thought i had the problem solved and now it compiles but it doesnt do things right.

 

by: andlaPosted on 1999-12-12 at 07:39:44ID: 2275250

First you put 'unsigned' everywhere you are sure no negative value can exist. This will also give you ability to put a higher number. Twice as big.

unsigned int i, hold, j, held;
for(unsigned int pass....
for(unsigned int pass....

I will check more...

 

by: weinrjPosted on 1999-12-12 at 07:58:15ID: 2275274

i doubt the warnings are causing the problem but they could be....

but if u look here: cout << "Is this an anagram: " << anagram(array1,array2);
// if true print YES if false, print NO



the cout is never printed, meaning the function is never called...somewhere else long the line has a problem....then when i get that printed i will see what is wrong w/ the function if anything....then i need to figure out in the cout if it passed or not and how to say that...

like if (true) cout << yes
if (false) cout << no

??

 

by: andlaPosted on 1999-12-12 at 08:11:43ID: 2275300

I just helped you get rid of the warnings. And along the way i found you program holds.

It's so simple yet hard to find so tell you about the story of 'j'

Once upon a time there where a 'j' that couldn't grow up. He was still young and he relly wanted to to tell the
for ( j = 0; j < strlen(test2) - 1; i++ )

loop that he wanted to grow up so he could leave the for loop. But 'i' told sorry you are to young so i have to look after you. This is the end of the sad story.

If you replace 'i' with 'j' the story ends with a happy ending.

Good luck!

 

by: andlaPosted on 1999-12-12 at 08:17:43ID: 2275307

The program works better if you remove the cin.get();

while(1)
{
cin.get(ch);
                  if(ch=='\n')
                  break;
                  //cin.get();
array1[i++] = char(tolower(ch));

}
    array1[i] = '\0';

cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
int j = 0;
while(1)
{
                  ch=cin.get();
                  if(ch=='\n')
                  break;
                  //cin.get();
                ch = char(tolower(ch));
                  array2[j] = ch;
                  j++;
}

 

by: andlaPosted on 1999-12-12 at 08:24:39ID: 2275315

The '\n' will alway be the last character in the buffer so it will never go in your strings.

Remember that the buffer i'm talking about is not your strings. It's kept somwhere in the data that iostream.h loaded. These data is called object.
There is an istream object for cin and a ostream object for cout. If you take a look at the tutorial for iostream you will find out that you can fix the loops that create your strings. For example take a look at cin.getline(..)


 

by: weinrjPosted on 1999-12-12 at 10:08:54ID: 2275458

ok...i put unsigned...the warnings are now gone.

i stupidly didnt realize the j++ thing...ooops....but that is in the function.  my program has never called the function yet since my cout isnt couting (is that even a word?)

Hmm, it is something w/ the string input.  I was taught to use cin.get() with the '\n'....My teacher likes while loops but i told him it is redundent since he has two couts and cins while i have one since i use do..while.

he agreed.  so i have to wonder what to do with the string input.

 

by: andlaPosted on 1999-12-12 at 10:24:45ID: 2275473

I mostly use while loops but sometimes its easier to use do while.

What you see is a 1 or 0 .
I saw that output i think a zero. So i don't se any errors. But another question is if the function wants what you want. Or the function do what you wants but later you see this is no what you want any more. It's better to cut a big function into smaller that way you can reuse your code instead of writing the whole big function from scratch.

 

by: andlaPosted on 1999-12-12 at 10:39:01ID: 2275488

I think the teacher thinks it's better to not do it his way as long it works. BTW does he know about experts-exchange ? You found a goldmine. :-)

 

by: weinrjPosted on 1999-12-12 at 11:10:03ID: 2275524

He isnt that internet savvy as most of the students are...He does put assignments on the web though.  When I run this, after I input the 2nd string nothing happens.  it just sits there cursor flashing (i need to do a control c to stop it)

 

by: andlaPosted on 1999-12-12 at 11:45:49ID: 2275563

It works for me. This is what i got so far.


//#include <windows.h>
#include <iostream.h>
#include <conio.h>//using namespace std;
#include <ctype.h>
#include <string.h>

bool anagram(char [], char []);

int main()
{
cout << "Welcome to Anagram Detector!\n\n>> ";
char ch, array1[256], array2[256];
int i = 0;
while(1)
{
cin.get(ch);
                  if(ch=='\n')
                  break;
                  //cin.get();
array1[i++] = char(tolower(ch));

}
    array1[i] = '\0';

cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
int j = 0;
while(1)
{
                  ch=cin.get();
                  if(ch=='\n')
                  break;
                  //cin.get();
                ch = char(tolower(ch));
                  array2[j] = ch;
                  j++;
}



                  array2[j] = '\0';
                  //MessageBox(0,array1,array2,0);//i'm not sure if this works with Borland.
                  //You can test to uncomment the line below and if you do don't forget
                  //to include windows.h

                  cout<<"array1="<<array1<<"      array2="<<array2<<endl;
                  //endl makes a new line.
                  cout << "Is this an anagram: " << anagram(array1,array2);
                  // if true print YES if false, print NO

                  return 0;
}

bool anagram(char test1[], char test2[]) {



unsigned int i, hold, j, held;

for ( unsigned int pass = 0; pass < strlen(test1) - 1; pass++ )
      for ( i = 0; i < strlen(test1) - 1; i++ )
            if (test1[i] > test1[i + 1])
            {
                  hold = test1[i];
                  test1[i] = test1[i+1];
                  test1[i+1]=hold;
            }

for ( unsigned int pass1 = 0; pass1 < strlen(test2) - 1; pass1++ )
      for ( j = 0; j < strlen(test2) - 1; j++ )
            if (test2[j] > test2[j + 1])
            {
                  held = test2[j];
                  test2[j] = test2[j+1];
                  test2[j+1]=held;
            }

    return (test1 == test2);

}

 

by: andlaPosted on 1999-12-12 at 11:48:24ID: 2275568

Remember to use copy and paste and dont write this code by hand. If you do you will not have any typo in your code.

 

by: weinrjPosted on 1999-12-12 at 11:51:02ID: 2275573

ok

i use ms visual c++ 6.0

 

by: andlaPosted on 1999-12-12 at 11:57:10ID: 2275581

Same as i. :-)

Compile and run yeeeehaaa!!

 

by: weinrjPosted on 1999-12-12 at 12:03:23ID: 2275593

ok...this compiles here too.

what does the messagebox thing do?
for the class the box is not needed, but for my own self learning, how can i make a box pop up, ask for input w/ a box and output results w/ a box.

andla...thnx

 

by: weinrjPosted on 1999-12-12 at 12:06:02ID: 2275598

the next step for me is priting yes or no, not 0 1....heeh this is quite fun now, no wonder why i took this course!

 

by: andlaPosted on 1999-12-12 at 12:11:12ID: 2275603

I hope it works out. Just tell me if you got any serious problem.
:-)

 

by: weinrjPosted on 1999-12-12 at 12:23:07ID: 2275619

andla---

can u tell me how to make the messagebox done throughout the enire project?

such as

Enter String: [         ]
in a box

then enter anagram of string: [      ]

function runs

string 1 and string 2 are anagrams
of each other or not in another box...
i think that will be cool just for me to learn....(not for the school part though)

 

by: weinrjPosted on 1999-12-12 at 12:35:55ID: 2275630

since i use cout << anagram()

how do i say

if anagram returns true print yes
if anagram returns false print no

 

by: andlaPosted on 1999-12-12 at 14:14:15ID: 2275715

This MessageBox is implemented as a standard control in you visual studio. If you want it to display an editbox in an dialogbox it will be more work. And since you work in the console enviroment it will be more problem. I can make simple working app for you but it will take you several days to get into. You vill have to learn how windows handle messages. There are two impotant parts a message sender and a message retriever. Remember don't stay to long with old C/C++. If you want to do the cool stuff you chould study directx sdk, windows programming and MFC.

About the print yes and no i only say it would not right to help you. I think your teacher ment that you should study. :-)
hint: Just read documentation about 'if'

Good luck!

 

by: weinrjPosted on 1999-12-12 at 14:23:01ID: 2275723

ok---thanks!!!!!

I will LEARN this....

and i would like to learn the cool stuff while I am learning the console stuff.

If posible, please do that, dont matter how long....The windows version w/ that input out put diaglogs, etc....and send the source....i never done visual programming before just console, the window apps part is later on,.

please send to jwnrb@cybernex.net

 

by: weinrjPosted on 1999-12-12 at 14:40:11ID: 2275737

the anagram returns 0 no matter what

i cant do an if because the output of the number is out already

 

by: andlaPosted on 1999-12-12 at 15:43:31ID: 2275762

Here you go.

_______________________________________
//project.cpp


#include <windows.h>
#include <iostream.h>
#include <conio.h>//using namespace std;
#include <ctype.h>
#include <string.h>

bool anagram(char [], char []);
BOOL WINAPI DlgProc(HWND,UINT,WPARAM,LPARAM);
char mystring[256];
char mymessage[256];
int main()
{


//cout << "Welcome to Anagram Detector!\n\n>> ";
strcpy(mymessage,"Welcome to Anagram Detector!");
DialogBox(0,MAKEINTRESOURCE( 10000 ),0,(DLGPROC)DlgProc);
char  array1[256], array2[256];
strcpy(array1,mystring);



//cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
strcpy(mymessage,"Please enter an anagram of the following:");
strcat(mymessage,array1);
DialogBox(0,MAKEINTRESOURCE( 10000 ),0,(DLGPROC)DlgProc);
strcpy(array2,mystring);


cout << "Is this an anagram: " << anagram(array1,array2);
// if true print YES if false, print NO
//*/
return 0;
}


BOOL WINAPI DlgProc(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
      


      switch(uMsg)
      {      
            


               case WM_COMMAND:      
                  
                    
                        SetWindowText(hwndDlg,mymessage);
      

                  GetWindowText(GetDlgItem(hwndDlg,101),mystring,255);
                   if( wParam == IDCANCEL )
                  {
                  
                        EndDialog( hwndDlg, TRUE );
                        //PostQuitMessage(wParam);
                  
                   return( TRUE );  
                        //break;
                  }  
                  
                  
      }
return( FALSE );
}









bool anagram(char test1[], char test2[]) {



unsigned int i, hold, j, held;

for ( unsigned int pass = 0; pass < strlen(test1) - 1; pass++ )
for ( i = 0; i < strlen(test1) - 1; i++ )
if (test1[i] > test1[i + 1])
{
hold = test1[i];
test1[i] = test1[i+1];
test1[i+1]=hold;
}

for ( unsigned int pass1 = 0; pass1 < strlen(test2) - 1; pass1++ )
for ( j = 0; j < strlen(test2) - 1; j++ )
if (test2[j] > test2[j + 1])
{
held = test2[j];
test2[j] = test2[j+1];
test2[j+1]=held;
}

    return (test1 == test2);

}    
______________________________________
//resource.rc
  #include <windows.h>

10000 DIALOG  DISCARDABLE  0, 0, 186, 95
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "My DialogBox"
FONT 8, "MS Sans Serif"
BEGIN
 EDITTEXT        101,11,34,160,15,ES_AUTOHSCROLL  
END
_______________________________________



 

by: andlaPosted on 1999-12-13 at 05:02:46ID: 2276740

Did you know that you can put functions in an if() ?

Try again. :-)

 

by: weinrjPosted on 1999-12-13 at 07:07:05ID: 2277100

in an if?? cool...thnx

 

by: weinrjPosted on 1999-12-13 at 07:14:10ID: 2277124

how do i insert resource script....also in my original lab i always get false no matter what....crazy

 

by: weinrjPosted on 1999-12-13 at 07:22:42ID: 2277154


  if (anagram(array1,array2) == true)
        cout << "YES!  Thats an anagram.";
  else
        cout << "NO!   Thats not an anagram.";
 

but it always says no....

and whats funnier is i did a debug

 cout << endl << "test1: " << test1 << endl << "test2: " << test2 << endl;

and it shows it works....

 

by: andlaPosted on 1999-12-13 at 07:38:36ID: 2277205

I believe an anagram is harder to make than that. When i studied the code listings they ususally used an extra file containing information that the anagram program could use. I don't really know what you have in plan but this code (test2[j] > test2[j + 1]) will check the ascii value and sort the characters in the string according to that value. I don't know much about anagram but if you give me a clear definition i can try to help you.

 

by: weinrjPosted on 1999-12-13 at 07:52:23ID: 2277242

how do i do the resource script??

from the other thing


"
....whether one is an anagram of the other -- that is, whether one character string is a permutation of the characters in the other string. For example, "dear" is an anagram of "read, as is "Dare". Note that we do not distinguish between uppercase and lowercase letters. " from the assignmetn

 

by: weinrjPosted on 1999-12-13 at 09:20:23ID: 2277523

just so u know----i got the program to work

/*
   Jonathan Weinraub
   anagram finder 2000

*/

#include <iostream.h> // input / output stream
#include <ctype.h>    // get
#include <string.h>   // string functions


bool anagram(char [], char []); // declaration statement

int main()
{
   cout << "Welcome to Anagram Detector!\n\n>> ";
   char ch, array1[256], array2[256]; // initialize strings to 256 charactors
   int i = 0; // initialize counter to zero
   while(true)   // starts loop  - also prevents '\n' from being stored
   {                     // in the array buffer
     cin.get(ch);
     if(ch=='\n')
        break;

   array1[i++] = char(tolower(ch));
}
   array1[i] = '\0'; // appends null charactor  
   cout << "\nPlease enter an anagram of the following: " << array1 << "\n>> ";
   int j = 0;
   while(true)
   {
     ch=cin.get();
     if(ch=='\n')
        break;
     ch = char(tolower(ch));
     array2[j] = ch;
     j++;
   }

  array2[j] = '\0';
 
 
   
 
  if (anagram(array1,array2) == true)
        cout << "YES!  Thats an anagram.";
  else
        cout << "NO!   Thats not an anagram.";
 
 

  cout << endl << endl;
  return 0;
}

bool anagram(char test1[], char test2[]) {

  /* This function will determine if something is an anagram or not
  by sorting the string using a bubble sort then comparing the two
  strings */
      
  unsigned int i, hold, j, held;

  for ( unsigned int pass = 0; pass < strlen(test1) - 1; pass++ )
    for ( i = 0; i < strlen(test1) - 1; i++ )
      if (test1[i] > test1[i + 1])
        {
        hold = test1[i];
        test1[i] = test1[i+1];           // sorts string1 using bubble
        test1[i+1]=hold;
        }

  for ( unsigned int pass1 = 0; pass1 < strlen(test2) - 1; pass1++ )
    for ( j = 0; j < strlen(test2) - 1; j++ )
      if (test2[j] > test2[j + 1])
        {
        held = test2[j];
        test2[j] = test2[j+1]; // bubble
        test2[j+1]=held;
        }
        
   if (strcmp(test1, test2) == 0)
         return true;
   else
         return false;

}



now--i would like to learn how the other program works once i know how to do a resource script

 

by: andlaPosted on 1999-12-13 at 09:47:18ID: 2277589

Ok the resource script is very simple. One of the first thing you learn in windows programmming is resource script.

1. Create a new file named resource.rc
2. In this file paste the code i gave you.
#include <windows.h>

10000 DIALOG  DISCARDABLE  0, 0, 186, 95
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "My DialogBox"
FONT 8, "MS Sans Serif"
BEGIN
 EDITTEXT        101,11,34,160,15,ES_AUTOHSCROLL  
END

3. Make sure this file is added to you project.

4. Compile and run.

:-)

 

by: weinrjPosted on 1999-12-13 at 09:51:01ID: 2277597

aight thnx

 

by: andlaPosted on 1999-12-13 at 09:55:22ID: 2277603

>>"dear" is an anagram of "read, as is >>"Dare"

I think you must have a script file of these words. The computer could not possible know what is words and what is not without a script to follow.

Did your teacher give any instruction how to create the anagram?

 

by: peakerchooPosted on 2003-05-24 at 23:25:14ID: 8579432

Hi weirj

I too am trying to do a similar thing that you are doing and am finding it more difficult that you.  I am wondering what did u write for the other files...
ie. ctype.h

thanks for your help

 

by: weinrjPosted on 2003-05-25 at 08:25:28ID: 8580296

hmm, i did this long ago.  i am trying to find my original source code.  but i belive what i did was do  a bubble sort.
so i sorted both arrays.

the reason why i used ctype was so i can convert all letters to one case, (lowercase).

once both strings were then converted to lowercase, and then bubble sorted, i had two strings now.
i then did a string compare.  if they were exactly the same, then they were a anagram.

i did this freshman year in college.  i am now a senior so i am sure i would had done it a bit differently now.  

good luck!

 

by: peakerchooPosted on 2003-05-26 at 02:15:07ID: 8583304

thanks for your help wienrj. you have been godsend.

One other question.

How do i write a function in there so that all non alphabetic characters are removed... ie. punctuation, spaces, digits.

and How do I write a function so that at the end it prompts me to see if I would like to repeat?

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...