LearnFrenzy
Sign in Take a free test

std::string · Find the Error · Question 7

Error: passing std::string to strlen Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <cstring>
#include <iostream>
#include <string>

int main() {
    std::string city = "Chennai";
    std::cout << std::strlen(city) << '\n';
    return 0;
}
  • A <cstring> is the wrong header
  • B strlen expects a const char*; a std::string does not convert automatically – use city.size() or std::strlen(city.c_str()) Correct
  • C city is too long
  • D strlen returns void
Correct Answer: Option B

std::string deliberately has no implicit conversion to const char*. For its length, size() is O(1) while strlen scans.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links