Hi there,
Could some1 tell me whats wrong with this code...I know i shudnt b using an int variable but whats the right one for a string...

#include <iostream.h>
  void main()
  {
  int a,b;
  cout <<"Enter the first name";
  cin >>a;
  cout <<"Enter the 2nd no";
  cin >>b;
  ((a=="Tom") && (b=="Pam")) ? cout<<"Yesss..." : cout<<"Noo";
  }

Thanx a million

Hello,

No, int variables and character / string variables are different types. You want to do something like this:

// Have to declare values and [size]
// Note that size must be large enough to handle the
// projected size of the word/sentance *and* the return character
// Overloads will overwrite other data in memory (BAD!)
// Compilers might handle overloads differently.

{
    char firstname[10], nextname[10];

    cout << "Enter the firstname: ";
    cin >> firstname;

}

Now, you also wanted to compare if Firstname == Tom, and Nextname == Pam.

Couple things to remember:

Tom <> tom, Tom <> tOm <> TOm
Pam <> pam

Error checking, my friend!

In your studies, you may have heard of the string processing library. You should use one function to make all the data ALL CAPS or all smalls, and use another function to compare the strings. Here is a hint... strcmp

Good Luck,

Christian

there is a really helpful library called <algorithm> that can help you with string manipulation and comparing etc. look it up online or a book or something...
good luck

Use string.h

strcmp(str1,str2);

returns 0 if they are equal

Note this will only work with c strings, if you want to use this function with string you will need to treat them as c style strings ie:

if ((int a = strcmp(stringa.c_str(), stringb.c_str())) == 0) {
   cout << "Match" << endl;
} else {
   cout << "No match" << endl;
}

With c++ I find it is easier to compare the strings with:

if (stringa == stringb) {
   cout << "Match" << endl;
} else {
   cout << "No match" << endl;
}

HTH
Ben

#include<iostream>
#include<string>

using namespace std;

void main()
{

    string s="hello";
    string t="hello";

    //std::string;

    if(s==t)
        cout<<"thek h"<<endl;
    else
        cout<<"e"<<endl;



}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Comments
Don't bump old threads for this
This article has been dead for over six months. Start a new discussion instead.