Archived

This topic is now archived and is closed to further replies.

Need help on String Compare

This topic is 5144 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi. I'm a 16, female from Boston. I really need some help on my program. I can't figure out what is wrong wtih my string compare. I'm not really good at this because I've been learning it for 11 weeks now at my internship. I guess you can say I'm a beginner and this isn't what i usually do. But I wanted to try somemthing new and get out of my box so if anyone can help me out. It will be much apperciated = ) This is just a part of the code that is not working please tell me why it isn't comparing properly. int add () { char news[60]; char last[60]; int age; int b, i; printf("Enter first name:"); scanf("%s", &news); printf("Enter last name:"); scanf("%s", &last); printf("Enter age:"); scanf("%d", &age); for(b = 0; b < 60; b++) { int result; result = strncmp( n.first, news, 30); if(result > 0) { printf("Not in Database"); } else if(result < 0) { printf("Not in Database"); } else if(result = 0) { printf("In database"); strcpy (n[n_used].first,news); strcpy (n[n_used].last,last); n[n_used].age= age; n_used++; } getche(); return 0; } [edited by - chanana on November 12, 2003 2:50:45 AM]

Share this post


Link to post
Share on other sites
else if(result = 0)

Two equals are better than one.


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]


[edited by - Fruny on November 12, 2003 2:52:44 AM]

Share this post


Link to post
Share on other sites
Another issue is that you're doing a string compare against what looks like a character array indexed by a uninitialized variable, the n[ i ]. Maybe you meant n[ b ] instead?

And, not to be picky, but that entire if block can be changed. Considering that the actions taken when result is less than 0 and result is greater than 0 are the same, it might be better to change it to:

if (result != 0) {
// stuff there
} else {
// other stuff
}

Less lines of code == less lines of code to go wrong.


edit: What compiler are you using? Most recent C compilers would have complained about (issued a warning on) both the use of an uninitialized variable and the assignment inside an if expression.

[edited by - SiCrane on November 12, 2003 3:55:24 AM]

Share this post


Link to post
Share on other sites