C++ String Assignment Error – Need Help!

0
5
Asked By CuriousCoder99 On

Hi there! I'm currently learning C++ in class and ran into a bit of a weird issue while working with strings. I've got two strings set up like this:

std::string str1 = "example";
std::string str2 = "example2";

I thought I could just assign str2 to str1 using:

str1 = str2;

However, my compiler throws an error saying "error: no viable overloaded '='" along with a message about a conversion from 'std::string' to 'const char*'. I was under the impression that both variables were the same type, so I'm confused. Any insights?

3 Answers

Answered By TechyTina88 On

It looks like there might be an issue with the way you've set up your code. You mentioned getting an error that doesn't match the example you provided, which usually means something's not quite lining up. Could you share the exact lines of code where you're seeing this error? That could help pinpoint the issue.

Answered By GadgetGuru42 On

From what you've described, everything should work fine with `std::string`. One possibility is that str1 could actually be a different type, like `char const*`. Just double-check that it's defined as `std::string` throughout to avoid any issues.

Answered By CodeNinja101 On

This error typically happens when str1 was declared as a `char const*` rather than `std::string`. It might be worth checking your code again to ensure that all your declarations are correct.

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.