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_nam开发者_运维技巧e = "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;
Convert the string to a c-string.
printf("Hello %s", p.first_name.c_str());
Also, since you're using C++, you should learn about cout as opposed to printf!
Use printf("Hello %s",p.first_name.c_str());
!
printf("Hello %s", p.first_name.c_str());
However, why aren't you using iostream, if you are using c++?
You cannot pass C++ std::string
objects into printf
. printf
only understands the primitive types like int
, float
, and char*
. Your compiler should be giving you a warning there; if it's not, crank up your warning level.
Since you're using C++, you really should be using std::cout
for text output, and that does understand std::string
objects. If you really have to use printf
for some reason, then convert the std::string
to a const char*
by calling the c_str()
method on it.
printf("%s")
accepts a c-style string which is terminated by a '\0'
. However, string
object is C++ object which is different from a c-style string. You should use std::cout
which is overloaded to handle string
type directly, as shown below.
std::cout << p.first_name;
精彩评论