w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
printf() confusion - printing (null) when trying to print string and printing correct value when printing buffer

The program has undefined behaviour because function printf is unable to output objects of type std::string. When format symbol %s is used the function supposes that the corresponding argument is a pointer of a string literal. So the function tries to output the object of type std::string as a string literal. To use correctly function printf with objects of type std::string you should convert them to strings using member function c_str() or data() (for C++ 2011). For example

 string is: %s of length %ul 
", theString.c_str(), theString.length());

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.