-8

This is the code:

char s[101], s1[101];
cin >> s >> s1;
cout << stricmp(s, s1);

I tried to declare s and s1 as std::string, but it didnt work. Can someone explain please why stricmp() works with char[] but not std::string?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • You should probably be a bit more specific when you say "it didn't work." What result are you expecting, and what result are you getting? – TrampolineTales Sep 11 '17 at 15:07
  • 1
    Just because I feel like you don't know about it and it is relevant - do you know what a `char*` is? – Error - Syntactical Remorse Sep 11 '17 at 15:07
  • 3
    you can declare `s` and `s1` as `std::string`, but instead of calling `stricmp(s, s1);` call it like `stricmp(s.c_str(), s1.c_str());` – Fureeish Sep 11 '17 at 15:07
  • 3
    *why is it possible only with chars ? Why cant I input them as strings.* This indicates to me that you don't understand the fundamentals of the language yet. Please learn the fundamentals of the language from [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – R Sahu Sep 11 '17 at 15:16
  • for case insensitive string comparison in C++, see also https://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – stefaanv Sep 11 '17 at 15:25
  • BTW, don't use `cin` with character arrays. The array lengths are not passed to `cin`, so there is a possibility of buffer overflow. – Thomas Matthews Sep 11 '17 at 15:34

2 Answers2

1

That is because stricmp() doesn' t take std::string values as arguments.

Use std::basic_string::compare() instead.

std::string s ("s");
std::string s1 ("s1");

if (s.compare(s1) != 0) // or just if (s != s1)
  std::cout << s << " is not " << s1 << std::endl;

If you need a case-insensitive comparison, you need to make your own function, maybe using std::tolower() as in this example, or just boost::iequals() as in this other example.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rama
  • 3,222
  • 2
  • 11
  • 26
0

You may want to consider converting the strings to all upper or all lower case before comparing:

std::string s1;
std::string s2;
std::cin >> s1 >> s2;
std::transform(s1.begin(), s1.end(),
               s1.begin(),
               std::tolower);
std::transform(s2.begin(), s2.end(),
               s2.begin(),
               std::tolower);
if (s1 == s2)
{
  std::cout << "s1 and s2 are case insensitive equal.\n";
}
else
{
  std::cout << "s1 and s2 are different.\n";
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154