printf() surprising console output
15,210
Solution 1
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;
Solution 2
Try
printf("* Debug %s \n", myString.c_str());
or better still:
std::cout << "* Debug " << mystring << std::endl;
Solution 3
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";
Author by
Jochen
Updated on August 24, 2022Comments
-
Jochen over 1 year
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);
-
Bret Kuhns over 10 years+1 for the "C++ way". The other two options should be ignored, IMO.
-
Sergey L. over 10 years@BretKuhns The question originally also had the C tag which someone removed.