0

i can't find what's wrong w/ my program. the output is wrong when i type long names and names w/ less similar letters (sorry for my english i'm a filipino)

#include <stdlib.h>
#include <iostream.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>

char name1[20],name2[20];
int count1[25],count2[25],temp1,temp2,total;

void flames(int num)
{
     switch(num)
     {
	       case 1: cout<<"friends";
	       break;
	       case 2: cout<<"lovers";
	       break;
	       case 3: cout<<"Anger";
	       break;
	       case 4: cout<<"Married";
	       break;
	       case 5: cout<<"Enemy";
	       break;
	       case 6: cout<<"Sweet";
	       break;
		}
      }



main()


{
int x,y;
 temp1=0;
 temp2=0;
    cout<<"Sample program: FlAMES"<<endl;
    cout<<"--------'------------'------------"<<endl;
    cout<<"enter name1 ";
    gets(name1);
    cout<<"enter name2 ";
    gets(name2);

    strupr(name1);
    strupr(name2);

    for(x=0;x<=25;x++)
    {
		     count1[x]=0;
		     count2[x]=0;
		     }

		     for(x=0;x<=20;x++)
		     {
				      count1[name1[x]-'A']++;
				      count2[name2[x]-'A']++;
				      }

				      for(x=0;x<=25;x++)
				      {
				 if( (count1[x]!=0) && (count2[x]!=0) )

		{							 temp1=count1[x]+temp1;										 temp2=count2[x]+temp2;
}
total = temp1+temp2;
}

flames(total%6);endl;

getch();
return 0;
}
2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Schol-R-LEA
0

The problem with the name length comes from using gets() , which doesn't check the size of the array it reads into; in this case, if the name is more than 20 characters long, it will overflow the buffer and cause a crash. You should always use fgets() instead, or better yet, use the C++ iostream functions such as cin.getline() .

BTW, you should always declare main() as returning an integer value explicitly. While some older compilers (such as the one you seem to be using) will accept an implicit value for functions, the C++ standard requires explicit return types, especially for main() , which must - I repeat, must - return an int , in order for it to be valid C++ code.

Speaking of older compilers, if you can, I recommend getting a newer compiler that follows the current language standard. I realize you might not have a choice in the matter, when it comes to school work, but you should at least be aware that the language officially defined in 1998 (and updated this year) is quite different in some respects than what was used before then. If you are allowed to, get one of the new free compilers/IDEs such as Code::Blocks or Visual C++ Express.

Edited by Schol-R-LEA: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.