Type of ternary expression

The type of the expression ‘1’ is char. The type of the expression (test ? 3 : ‘1’) is at least int (or an unsigned version thereof; portably it is std::common_type_t<int, char>). Therefore the two invocations of the << operator select different overloads: The former prints the character as is, the latter formats the integer … Read more

How to disable cout output in the runtime?

Sure, you can (example here): int main() { std::cout << “First message” << std::endl; std::cout.setstate(std::ios_base::failbit); std::cout << “Second message” << std::endl; std::cout.clear(); std::cout << “Last message” << std::endl; return 0; } Outputs: First message Last message This is because putting the stream in fail state will make it silently discard any output, until the failbit … Read more

how to print a string to console in c++

yes it’s possible to print a string to the console. #include “stdafx.h” #include <string> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string strMytestString(“hello world”); cout << strMytestString; return 0; } stdafx.h isn’t pertinent to the solution, everything else is.

How to remove last character put to std::cout?

You may not remove last character. But you can get the similar effect by overwriting the last character. For that, you need to move the console cursor backwards by outputting a ‘\b’ (backspace) character like shown below. #include<iostream> using namespace std; int main() { cout<<“Hi”; cout<<‘\b’; //Cursor moves 1 position backwards cout<<” “; //Overwrites letter … Read more

std::cout won’t print

Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself. std::cout << “Hello” << std::endl; std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing … Read more

What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?

Generally you use std::cout for normal output, std::cerr for errors, and std::clog for “logging” (which can mean whatever you want it to mean). The major difference is that std::cerr is not buffered like the other two. In relation to the old C stdout and stderr, std::cout corresponds to stdout, while std::cerr and std::clog both corresponds … Read more