...

View Full Version : C++ Newbie - "char matching"



Samppa
02-05-2005, 07:18 PM
Right, I'm new to C++, and I've been having trouble with the following code.
A dumbed down version (especially the if bracket):


#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. :/

aman
02-05-2005, 10:40 PM
Read the post I made in this thread (http://www.codingforums.com/showthread.php?t=50408&highlight=string), especially the part I posted about comparing strings.

abbeyroadd
02-06-2005, 01:41 AM
Read the post I made in this thread (http://www.codingforums.com/showthread.php?t=50408&highlight=string), 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.



#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...

;)

Samppa
02-06-2005, 09:45 AM
Well thanks to both of you :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum