C++和printf - 奇怪的字符输出

Bud*_*Joe 7 c++ printf console-application

我是C++的完全新手,但不是Java,C#,JavaScript,VB.我正在使用Visual Studio 2010中的默认C++控制台应用程序.

在尝试做printf我得到一些奇怪的字符.每次都不一样,告诉我他每次运行时都会看到不同的内存位置.

码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 10

问题是printf/ scanf不是类型安全的.你正在提供一个期望a 的std::string对象.printfconst char*

解决这个问题的一种方法是写

printf("Hello %s", p.first_name.c_str());
Run Code Online (Sandbox Code Playgroud)

但是,由于您使用C++进行编码,因此优先使用I/O流优先于printf/ scanf:

std::cout << p.first_name << std::endl;
std::cin >> c;
Run Code Online (Sandbox Code Playgroud)