LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Find the Error · Question 7

Error: passing a string_view where std::string& is needed Answer, explanation & discussion

  • Find the error
  • Medium
  • 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 <iostream>
#include <string>
#include <string_view>

void append_suffix(std::string& s) { s += ".txt"; }

int main() {
    std::string_view name = "notes";
    append_suffix(name);
    std::cout << name << '\n';
    return 0;
}
  • A string_view cannot be printed
  • B A string_view is a read-only view and does not convert to std::string&; create a std::string from it (std::string s{name};) and modify that Correct
  • C append_suffix must be a template
  • D .txt is invalid
Correct Answer: Option B

The conversion string_view → std::string is explicit because it allocates.

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