Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jul 2004
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    C++ Newbie - "char matching"

    Right, I'm new to C++, and I've been having trouble with the following code.
    A dumbed down version (especially the if bracket):

    Code:
    #include <iostream>
    #include <stdlib.h>
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
        char name1[256], name2[256];
    
        cout << "What is your name? "; gets(name1);
    
        cout << "\nWelcome "<< name1 <<endl;
        cin.get();
    
        cout << "\nPlease insert your name: ";
        cin.getline ( name2, 256 );
        cin.get();
        
        if ( name1 == name2  ) {
        cout << "\nHi!";
        cin.get();
        return 0;
    }
        else {
        cout << "\nBye.";
        cin.get();
        return 0;
    }
    The part I'm having trouble with is the if bracket. How would I code that if name1 matches name2 it'd say "Hi", and if they didn't match, it'd say "Bye". I've been having trouble with that for the last couple of days. :/

  • #2
    Regular Coder
    Join Date
    Oct 2004
    Posts
    230
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Read the post I made in this thread, especially the part I posted about comparing strings.

  • #3
    New Coder
    Join Date
    Nov 2004
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by aman
    Read the post I made in this thread, especially the part I posted about comparing strings.
    Good advice in that thread.

    Samppa it's good that you are starting out with char arrays and pointers before getting to utilize the "nice" strings. Read the code in that thread for some help...but in the mean time I fixed up you're code to make it a little cleaner and to show you what you have to look forward to, good luck.

    Code:
    #include <iostream>
    using std::string;
    using std::cin;
    using std::cout;
    
    int main(void)
    {
        // Declare the strings.
        string name1, name2;
    
        //  Get input.
        cout << "What is your name: ";
        getline(cin, name1);
    
        //  Get input...again.
        cout << "What is your other name: ";
        getline(cin, name2);
    
        // An easy IF check.
        if (name1 == name2) 
    	cout << "\nHi!";
        else
    	cout << "\nBye.";
    }
    Hope this helps...


  • #4
    New to the CF scene
    Join Date
    Jul 2004
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Well thanks to both of you


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •