Need help on String Compare
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]
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]
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]
Another issue is that you're doing a string compare against what looks like a character array indexed by a uninitialized variable, the n. Maybe you meant n instead?<br><br>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:<br><pre><br>if (result != 0) {<br> // stuff there<br>} else {<br> // other stuff<br>}<br> </pre> <br>Less lines of code == less lines of code to go wrong.<br><br><br>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. <br><br><SPAN CLASS=editedby>[edited by - SiCrane on November 12, 2003 3:55:24 AM]</SPAN>
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement