Challenge - 5 Problems
Character vs String Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of character and string comparison
What is the output of this C++ code snippet?
C++
#include <iostream> #include <string> int main() { char c = 'a'; std::string s = "a"; if (c == s) { std::cout << "Equal" << std::endl; } else { std::cout << "Not Equal" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Think about the types being compared: char and std::string.
✗ Incorrect
In C++, you cannot directly compare a char and a std::string using '=='. This causes a compilation error because the types are incompatible.
❓ Predict Output
intermediate2:00remaining
Comparing char with string using c_str()
What is the output of this C++ code?
C++
#include <iostream> #include <string> #include <cstring> int main() { char c = 'a'; std::string s = "a"; if (std::strcmp(&c, s.c_str()) == 0) { std::cout << "Equal" << std::endl; } else { std::cout << "Not Equal" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Consider what &c points to and if it is a proper C-string.
✗ Incorrect
The expression &c points to a single character, but it is not null-terminated. strcmp expects null-terminated strings, so this causes undefined behavior and likely a runtime error.
❓ Predict Output
advanced2:00remaining
Output of comparing char and string with explicit conversion
What is the output of this C++ code?
C++
#include <iostream> #include <string> int main() { char c = 'a'; std::string s = "a"; if (std::string(1, c) == s) { std::cout << "Equal" << std::endl; } else { std::cout << "Not Equal" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Look at how the char is converted to a string before comparison.
✗ Incorrect
std::string(1, c) creates a string of length 1 containing the character c. Comparing this string to s which is "a" results in equality.
❓ Predict Output
advanced2:00remaining
Comparing char and string with operator== overload
What is the output of this C++ code?
C++
#include <iostream> #include <string> int main() { char c = 'a'; std::string s = "a"; if (c == s[0]) { std::cout << "Equal" << std::endl; } else { std::cout << "Not Equal" << std::endl; } return 0; }
Attempts:
2 left
💡 Hint
Check what s[0] returns and how it compares to c.
✗ Incorrect
s[0] returns a char, so comparing c and s[0] is a valid char-to-char comparison. Both are 'a', so output is "Equal".
🧠 Conceptual
expert2:00remaining
Why direct char and string comparison fails in C++
Why does the following code fail to compile in C++?
char c = 'a';
std::string s = "a";
if (c == s) {
// ...
}
Choose the best explanation.
Attempts:
2 left
💡 Hint
Think about type compatibility and operator overloading in C++.
✗ Incorrect
C++ does not provide an operator== overload to compare a char directly with a std::string. They are different types, so the compiler cannot resolve the comparison.