string "equal to" don't work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • prinze
    New Member
    • Jan 2011
    • 1

    string "equal to" don't work

    why does s2>s1 dont work and also the "equal to", it always shows "is greater than" whenever i compile it.

    Code:
    #include<iostream.h>
    #inlcude<conio.h>
    #inlcude<string.h>
    #include<stdio.h>
    
    main()
    {
    clrscr();
    char s1[40];
    char s2[40];
    
    cout<<"Enter 1st String:";
    gets(s1);
    cout<<"Enter 2nd String:";
    gets(s2);
    
    strcmp(s1,s2);
    
    if(s1>s2)
    {
    cout<<s1<<" is greater  than "<<s2;
    }
    else if (s2>s1)
    {
    cout<<s2<<" is greater than "<<s1;
    }
    else
    {
    cout<<s1<<" is equal to "<<s2;
    }
    
    getch();
    return 0;
    }
    Last edited by Niheel; Jan 14 '11, 01:00 AM. Reason: code tags
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    s1 and s2 are char arrays
    Code:
    char s1[40];
    char s2[40];
    so the comparison
    Code:
    if(s1>s2)
    {
    is comparing the addresses of s1 and s2 not the contents
    to compare the contents use strcmp


    e.g.
    Code:
    if(strcmp(s1,s2)>0)
    {
    cout<<s1<<" is greater than "<<s2;
    }
    are you confusing C strings (arrays of char) with C++ string objects

    where you can use the > == and < operators to compare string contents

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      It is a very bad idea to mix the C++ stream handling classes cout with the C stream handling classes gets(s1);

      If you are going to use cout for output use cin for input. Alternatively use printf or puts for output.

      If you are not switching to cin then DO NOT USE gets(s1); it is very unsafe as it provides no protection against buffer overwriting. use fgets(s1, sizeof s1, stdin); which prevents buffer overwriting.

      Comment

      Working...