toupper compare array to string

I need to compare user input to an array and find the index. I want to use toupper bot having some trouble with the reference to array.

This is the current line:
if (allCities[index].city == input)

I want to do this:
if (toupper(allCities[index].city) == toupper(input))
or
if (allCities[index].toupper(city) == toupper(input))

I get an error on the first parameter becuase it is an int. Have even tried converting to index just before the compare in the above line, but still thinks I am comparing int with string.
Since toupper converts only a single char you need a loop to convert the entire input:

http://www.cplusplus.com/reference/cctype/toupper/
Last edited on
See the _strupr function in string.h
The best answer I could find is this:

std::transform(input.begin(), input.end(),input.begin(), ::toupper);

works perfect and converts entire string....
There's also boost::algorithm::to_upper(input)

demo: http://ideone.com/zkIE2x
ref: http://www.boost.org/doc/libs/release/doc/html/boost/algorithm/to_upper.html

As for case-insensitive comparison, there's boost::iequals(str1, str2))

demo (comparing array and string, as in OP): http://ideone.com/f21pJC
ref: http://www.boost.org/doc/libs/release/doc/html/boost/algorithm/iequals.html
Last edited on
The problem with that approach is that it has to modify both strings, so it can't be used with const strings.

I have to admit that in this kind of situation I use _stricmp/stricmp (VC++, MinGW) or strcasecomp. Wrapped up so the evil, platform-specific code is hidden away...

1
2
3
4
5
6
7
8
inline bool equalNoCase(const std::string& lhs, const std::string& rhs) {
    return (0 == _stricmp(lhs.c_str(), rhs.c_str()));
}

// etc

if (equalNoCase(allCities[index].city, input))
...


but there are more thorough ways to go about it:

Case insensitive string comparison in C++
http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c

In more careful code I use boost::iequal, or equivalent code.

Andy

_stricmp, _wcsicmp, _mbsicmp, _stricmp_l, _wcsicmp_l, _mbsicmp_l
http://msdn.microsoft.com/en-us/library/k59z8dwe%28v=vs.100%29.aspx

strcasecomp
http://pubs.opengroup.org/onlinepubs/009695399/functions/strcasecmp.html
Last edited on
Topic archived. No new replies allowed.