Access violation reading location 0xCC006968.

I understand it’s a stupid question but I just don’t understand the answer.

The Code:


#include <iostream>
#include <string>
using namespace std;

int main()
{
	cout << "What's Your Name?" << endl;
	string hay;
	hay = "hi";
	string name;
	cin >> name;
	printf("hay%s, name%s
",hay,name);
	return 0;
}

Here’s the full error:

Unhandled exception at 0x5DFFFB53 (msvcr120d.dll) in MrFirstApp.exe: 0xC0000005: Access violation reading location 0xCC006968.

I think it has something to do with the printf/the %s in the code.

If you answer, please explain this to me, I just started C++ and I’m awful. Also could someone explain why there’s a
?

Thanks!

is a linebreak.

To be honest I wouldn’t be trying to do vanilla C++ inside UE, I’d look at the UE framework and take it from there. For example:

  1. Make a new plugin module
  2. Use the plugin module startup as your entry point
  3. Use UE_LOG() instead of printf()

That’s a reasonable first test to validate that you’re writing code and compiling and you’re actually inside UE as well. I’ve just been through that myself and it wasn’t overly bad.

Another option would be to make a custom blueprint, which is a bit verbose but also very easy once you get into it.

Thanks for the advice but are you able to answer the original question? How can I fix the printf without changing printf to something else?

To answer your question, printf expects a variable of type const char* when it sees %s; however, you’re passing in a variable of type std::string.
This didn’t compile for me on g++ or Visual Studio so I’m not sure how you got this far, but it works fine when I use:


printf("hay%s, name%s
",hay.c_str(),name.c_str());

The c_str() function returns the std::string as a char array.

When I did this, ‘hayhi nameWill’ got printed when all that I wanted to print was ‘hi Will’

Any help?

It’s because all “%s” does is tell printf to replace it with whatever is in the first argument after the string (because this is the first occurrence of %s. Note also your program will die if the first argument after the string is not actually a string as there are different control sequence for different types of data). In this case, the first argument after the string is hay.c_str() which contains the string “hi”

If all you wanted to do was print “hi Will” then your printf call should instead look like


printf("%s, %s
", hay.c_str(), name.c_str()); 

If you still have questions, I suggest you read the documentation for printf here: printf
When you get into actual Unreal C++ you’ll be pleased to find out that UE_LOG works very similarly to printf, so understanding how this works now will probably be helpful.

Great thank you!