I'm a complete newb to C++, but not to Java, C#, JavaScript, VB. I'm working with a default C++ console app from Visual Studio 2010.
In trying to do a printf I get some strange characters. Not the same each time which tells me they may be looking at different memory location each time I run it.
Code:
#include "stdafx.h"
#include <string>
using namespace std;
class Person
{
public:
string first_name;
};
int _tmain(int argc, _TCHAR* argv[])
{
char somechar;
Person p;
p.first_name = "Bruno";
printf("Hello %s", p.first_name);
scanf("%c",&somechar);
return 0;
}
The problem is that printf
/scanf
are not typesafe. You're supplying a std::string
object where printf
expects a const char*
.
One way to fix this is to write
printf("Hello %s", p.first_name.c_str());
However, since you're coding in C++, it's a good idea to use I/O streams in preference to printf
/scanf
:
std::cout << p.first_name << std::endl;
std::cin >> c;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With