Why am I getting an assignment error between two strings in C++?

0
4
Asked By CuriousCoder92 On

I'm currently learning C++ and working with strings. I've encountered a weird problem: I have two string variables defined as follows: `std::string str1 = "example";` and `std::string str2 = "example2";`. When I try to assign `str2` to `str1` using `str1 = str2;`, I receive an error in my compiler that says "error: no viable overloaded '='" and mentions something about no known conversion from 'std::string' to 'const char *'. I'm confused because I thought these strings were of the same type. Can anyone help me figure out what's going wrong?

2 Answers

Answered By StringSleuth77 On

This type of error usually occurs when `str1` is of type `char const*` instead of `std::string`. You might want to ensure that both are indeed `std::string` types. Check to see how you're declaring them!

CuriousCoder92 -

Does a declared string automatically convert to a 'char const*' in some scenarios?

Answered By CodeNinja42 On

You probably simplified your example a bit, as what you described should compile without errors. Can you double-check what compiler you're using? It's possible you have one of the strings defined as a pointer or marked in a way that's different from what you mentioned.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.