Alex Rivera | Logout

C++ and printf - strange character output

Asked 2011-10-14T15:12:37.843
9

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;
}
Edit
Report

2 Answers

13

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;
answered 2011-10-14T15:15:19.930
4

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!

answered 2011-10-14T15:16:05.843

Your Answer