C ++ and printf - weird character output

I am a complete newb for C ++, but not for Java, C #, JavaScript, VB. I am working with the default C ++ console application from Visual Studio 2010.

When I try to do printf, I get some weird characters. Not every time, every time I am told that every time I run it, they can look at a different place in memory.

The 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; } 
+6
source share
6 answers

The problem is that printf / scanf are not typical. You supply an object std::string , where printf expects const char* .

One way to fix this is to write

 printf("Hello %s", p.first_name.c_str()); 

However, since you are coding in C ++, it is recommended that you use I / O streams, preferring printf / scanf :

 std::cout << p.first_name << std::endl; std::cin >> c; 
+8
source

Convert string to c-string.

 printf("Hello %s", p.first_name.c_str()); 

Also, since you are using C ++, you should learn about cout, not printf!

+4
source

Use printf("Hello %s",p.first_name.c_str()); !

+2
source
 printf("Hello %s", p.first_name.c_str()); 

However, why don't you use iostream if you use C ++?

+2
source

You cannot pass C ++ std::string objects to printf . printf only understands primitive types like int , float and char* . Your compiler should give you a warning; if not, return your warning level.

Since you are using C ++, you really need to use std::cout to output text, and this is understood by std::string objects. If for some reason you really need to use printf , then convert std::string to const char* by calling the c_str() method on it.

+2
source

printf("%s") accepts a c-style string that ends with the character '\0' . However, a string object is a C ++ object that is different from a c-style string. You must use std::cout , which is overloaded to handle the string type directly, as shown below.

 std::cout << p.first_name; 
0
source

Source: https://habr.com/ru/post/899308/


All Articles