Member Avatar for v3ga

Hi everyone just started Daniweb!
I have been using devcpp for some time.I am trying to make a switch from DevCpp to Visual Studio but find the latter confusing having so many options. Recently, I did a console application that will accept a word from user and prints its anagrams. The code compiled and ran successfully. But when I try to compile the same code using Visual studio the program gives wrong output. The code is given below

//Data Structure Class Assignment
//Anagrams Program
//Accepts a word and prints its anagrams.

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

//for sorting characters in an array using insertion sort
void CharSort (char a[],int n)
{   
    int i, j = 0;
    int key;

    for (i = 1; i < n; j = i, i++) 
    {
        key = a[i];
        while (j >= 0 && a[j] > key) 
        {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

//for finding sum of ASCII values of the characters of a string
int CharSum(char a[],int n)
{   
    int sum=0,i;
    for(i=0;i<n;i++)
    sum+=a[i];
    return sum;
}
//for comparing 2 words to see whether they are anagrams
bool isanagrams(char a[], char b[],int alen,int blen)
{
     if(alen!=blen)
     return false;
     if(CharSum(a,alen)!=CharSum(b,blen))
     return false;
     CharSort(b,blen);//CharSort(a,alen) is not required because it is sorted before passing to this function 
     if(strcmp(a,b)==0)
     return true;
}

using namespace std;
int main()
{
     ifstream fin;
     fin.open("dict.txt",ios::in);
     if(!fin)
     {
             cout<<"File Handling Error\n";
             cin.get();
             exit(1);
     }
     char keyword[20],dictword[20],copy[20];//for user input word, dictionary word from file and a copy of dict word for output
     bool flag;
     int p,q;//for storing strlen of the 2 words.
     cout<<"ANAGRAM SOLVER\n"
         <<"***************\n";
     while(1)
     {
     
     fin.clear();
     fin.seekg(0);
     int count=0;
     cout<<"Enter the word (0 to exit)\n";
     cin>>keyword;
     if(keyword[0]=='0')
     break;
     p=strlen(keyword);
     CharSort(keyword,p);
     //loop begins checking each word of file till EOF is reached.
     while(!fin.eof())
     {                fin>>dictword;
                      q=strlen(dictword);
                      int i;
                      for(i=0;dictword[i]!='\0';i++)
                      copy[i]=dictword[i];
                      copy[i]='\0';
                      if(isanagrams(keyword,dictword,p,q))
                      {     count++;
                            cout<<count<<'.';
                            for(int j=0;copy[j]!='\0';j++)
                            cout<<copy[j];
                            cout<<endl;
                      }
                      
      }
     if(!count)
     cout<<"NO ANAGRAMS FOUND\n";
     //loop ends.set file pointer to start of file.
     }
     return EXIT_SUCCESS;
}

Pls help me with the problem.

What error did you get when you try to compile?

Member Avatar for v3ga

The compilation was successful but at runtime the program gives wrong output, i.e. it gives as output far too many words most of which are not anagrams of the input word

In CharSort, why is "key" an int?

Member Avatar for v3ga

In CharSort, why is "key" an int?

I want to compare their ASCII codes. When I directly compare a and a[j] it gives wrong output at runtime so put key=a so that key will have ASCII code of a and when I run the program it runs correctly. key= a implies key= (int) a and a[j]>key implies a[j]> (int) key [atleast thats how it is in devc++ I dunno anything about visual studio]

Member Avatar for v3ga

I would like to make my question clear. My problem is with difference in c++ language rules between devc++ and visual c++ 2008. My program RUNS SUCCESSFULLY in devc++ but fails to do so in visual studio(it compiles successfully but gives wrong answers).

Member Avatar for v3ga

Here is little more info. In program compiled by visual studio, all words are output which have the same CharSum(sum of ASCII codes) as the input word. It does not compare the sorted character arrays.
eg: If word "boss" is input the correct program compiled by devc++ gives output:
1.boss
2.sobs
The program compiled by visual studio gives output:
1.anus
2.asps
3.awls
4.boss
5.bums
6.burn
7.cloy
8.coup
9.dusk
10.font
11.gist
12.grey
13.gush
14.hews
15.hiss
16.horn
17.hugs
18.iris
19.jays
20.kips
21.laws
22.less
23.lint
24.loom
25.loth
26.luau
27.mosh
28.move
29.nook
30.oats
31.ohms
32.oils
33.opes
34.part
35.pass
36.pent
37.peso
38.poll
39.pose
40.prep
41.prof
42.rapt
43.rems
44.saps
45.shew
46.silo
47.skip
48.slaw
49.sobs
50.soil
51.soli
52.song
53.spas
54.tarp
55.trap
56.tuck
57.vies
58.vise
59.warm
60.weir
61.wire
62.yipe
I notice that all these words have character ASCII sum = 439.
So visual studio has any problems with strcmp()? or with the way I sort the character array?

So visual studio has any problems with strcmp()?

Kind of looks that way, though that's pretty hard to believe. Have you stepped through your isanagrams() routine in the debugger?

BTW: you have some other errors in main(), but they're not related to this issue.

The error is in the function isanagrams. If you turn on the warnings on the compiler.
[No I don't know how to do it on Visual studio.] You will see that you are told that
fro that funciton: warning: control reaches end of non-void function.

The problem is that the value is the undefined, so you many get a true even if the strcmp(a,b) is not equal to 0.

Try changing the conditional to this: return (strcmp(a,b)==0); Additionally, you read the dictionary words into a VERY short character array (20 characters). I made the mistake of testing the program with a typical English dictionary file, and core dumped the program, because the longest words in the english dictionary are over 20 letters long. It is often important to be very careful about reading strings directly in to character arrays without checks on the maximum number of character that are allowed to be read.

Ah, very good catch, Stu.

Your solution would work, but I'd prefer to see the OP create a return code variable, set it it in the routine, and have a simple

return rc;

at the end.

Member Avatar for v3ga

The error is in the function isanagrams. If you turn on the warnings on the compiler.
[No I don't know how to do it on Visual studio.] You will see that you are told that
fro that funciton: warning: control reaches end of non-void function.

The problem is that the value is the undefined, so you many get a true even if the strcmp(a,b) is not equal to 0.

Try changing the conditional to this: return (strcmp(a,b)==0); Additionally, you read the dictionary words into a VERY short character array (20 characters). I made the mistake of testing the program with a typical English dictionary file, and core dumped the program, because the longest words in the english dictionary are over 20 letters long. It is often important to be very careful about reading strings directly in to character arrays without checks on the maximum number of character that are allowed to be read.

Thanks a lot. That worked. How value of strcmp(a,b) can be undefined?

Regarding the size, I thought 20 was a pretty safe limit. Just now I ran a code(taking array size 40) to find the word with max length and found max length to be 24 ("electroencephalographies"). Guess I should have checked.

It isn't the return of the routine that's undefined.

Your routine isanagrams doesn't always set a return value. The times that the tests all fail, you get a random bool value passed back. Actually, it's not random; it's more likely to return true than false.

I would encourage you not to program like this in the future. Create a return code variable, and set it in your routine (several places if necessary), but only call return once.

Member Avatar for v3ga

Kind of looks that way, though that's pretty hard to believe. Have you stepped through your isanagrams() routine in the debugger?

BTW: you have some other errors in main(), but they're not related to this issue.

Sorry if I sound noobish but I have never used a debugger. Can u pls direct me to a link where I can learn about debugging?
The program compiles successfully and after editing the code of CharSort like StuXYZ told, I got correct output so what's the error?

My comment about how to use returns wasn't meant to address an error. I was just suggesting a cleaner, more professional way to code. Take it for what it's worth.

Regarding debugging...I don't really know what to tell you. I use Qt for my IDE, and it has a front end for gdb, so that's all I use. Once you learn a few commands, such as step, step into, and some others, you're good for most of what you're likely to need.

First off, the reason for your error might be better understood if we consider this piece of code:

bool function(int a,int b)
{
   bool retValue;              // Value not set!!!
   if (a==b) retValue=true;
   return retValue;
}

That is in-essence what you have done. You actually hide it a little by not putting a
return statement at the end of your code, but it is the same code. If you need to see that, take your original and ADD a line after the last statement before the } in isanagram std::cout<<"HERE"<<std::endl; and you will see that you are then going to exit the function without an explicit return statement.

As to debugger, yes you will need to learn to use one but not now. Understanding, how to put print statement (std::cout) and fundamentally looking at your code will help more.

Member Avatar for v3ga

Since my problem is solved I am marking it closed. Thanks everyone

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.