3

I need to develop with C++ after a break of a few years. Anyway, I got problems following the tutorials I am currently reading. After writing the following code-snippet I expected to see 'Hello World' in my console, but I am only able to see 'Debug: StrangeChars'; What went wrong?

std::string myString("Hello World"); 
printf("* Debug: %s \n", myString);
Gianmarco
  • 2,536
  • 25
  • 57
Jochen
  • 1,746
  • 4
  • 22
  • 48

5 Answers5

16

printf relies on you passing the right arguments. %s requires a char *, you passed a std::string.

Try (C way)

char myString[] = "Hello World";
printf("* Debug: %s \n", myString);

Or (Hybrid C/C++ way)

std::string myString("Hello World"); 
printf("* Debug: %s \n", myString.c_str());

Or the C++ way:

std::string myString("Hello World"); 
std::cout << "* Debug " << myString << std::endl;
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
3

Try

printf("* Debug %s \n", myString.c_str());

or better still:

std::cout << "* Debug " << mystring << std::endl;
graham.reeds
  • 16,230
  • 17
  • 74
  • 137
1

The string type referenced by printf's %s% is not the same as std::string.

In fact, when printf was specified, std::string did not even exist. In C++ you should use std::cout instead, which works as expected:

#include <iostream>
 [...]

std::string myString("Hello World"); 
std::cout << "* Debug: " << myString << " \n";
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
0

Use myString.c_str(); You're trying to output an object as a string. There's no conversion between std::string and char *

0

printf is a C function and expects a c-string, a char* which is just a pointer to a place in memory where the contexts of the string reside. It assumes the string goes as far as the next '\0' byte and will print the contents of the memory from the address passed as pointer up to that point (the next '\0').

std::string is a class with several members. Apart from the actual string, it stores, for example, the current size. Besides, you did not pass a pointer to the string.

If you want to use std::string with printf, you'll have to call the c_str() method on the string object. This method returns the content of the string object as char* / c-string and should always be used when using string objects with c-function that expect c-strings.

printf("* Debug: %s \n", myString.c_str());
b.buchhold
  • 3,837
  • 2
  • 24
  • 33