Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and printf - strange character output

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;
}
like image 308
BuddyJoe Avatar asked Oct 14 '11 15:10

BuddyJoe


1 Answers

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;
like image 196
NPE Avatar answered Sep 28 '22 14:09

NPE