简体   繁体   中英

How to compare two structure strings in C++

Ok, so this week in class we're working with arrays. I've got an assignment that wanted me to create a structure for an employee containing an employee ID, first name, last name, and wages. Then it has me ask users for input for 5 different employees all stored in an array of this structure, then ask them for a search field type, then a search value. Lastly, display all the information for all positive search results.

I'm still new, so I'm sure it isn't a terribly elegant program, but what I'm trying to do now is figure out how to compare a user entered string with the string stored in the structure... I'll try to give all the pertinent code below.

struct employee { int empid, string firstname, string lastname, float wage };
employee emparray[] = {};
employee value[] = {};

//Code for populating emparray and structure, then determine search field etc.

cout << "Enter a search value: ";
cin >> value.lastname;  

for(i = 0; i < 5; i++) {
if(strcmp(value.lastname.c_str, emparray[i].lastname.c_str) == 0) {
    output();
}
}

Which... I thought would work, but it's giving me the following error..

Error   1   error C3867: 'std::basic_string<_Elem,_Traits,_Alloc>::c_str': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Alloc>::c_str' to create a pointer to member d:\myfile

Any thoughts on what's going on? Is there a way to compare two .name notated strings without totally revamping the program? IF you want to drill me on best practices, please feel free, but also please try to solve my particular problem.

It should be:

strcmp(value.lastname.c_str(), emparray[i].lastname.c_str()) == 0)

Also note that you don't have to do this as using strcmp is used for C-Style strings. Since you're using C++, you can use the overloaded == operator for comparing string objects.

That is:

value.last_name == emparray[i].lastname

Note that the overloaded == operator for strings doesn't do case insensitive string comparisons - but, you can implement such functionality on your own.

Other suggestions: use vectors instead of arrays and, you should specify a size for your arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM