Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about string variables and "if else" statement

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
OK- I just started my C++ class at school and found something interesting (BTW- I have NO prior experience with C++, just a little VB). We are using Borland C++ 3.1 also.

I cannot get an "if else" statement to process a string variable input by a user. No matter what is typed in, it seems to bypass the If statement and go directly to the "else" statement.

For example:

char name [20];

cout << &quot;Enter Name:&quot;;
gets(name);

if (name == &quot;Scott&quot;)
cout << &quot;Correct&quot;;

else
cout << &quot;Incorrect&quot;;


forgive me, I am doing this from memory, so my code may be a little off......but, what is the correct way to define a variable input by the user and then process that info??
 
you MUST use strcmp

if( strcmp(name,&quot;Scott&quot;) == 0)
{
// true
}
else
{
// false
}


strcmp is weird when you first use it as well. strcmp returns zero when true <0 if argument 1 is less then argument 2 and >0 if 2 is greater then one

Matt
 
try using strstr as well, strcmp will do it, but it is a little goofy in it's methods, I personally prefer strstr

if (strstr(name, scott))
{
/* found the name... */
}
else
{
/* didnt find the name */
} Cyprus
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top