Is there any way to know the size of what will be printed to standard output in C++?
An answer to this question on Stack Overflow.
Question
For example, if I use the following:
cout << "hello world";
Is there any way to know the size of what's being printed to stdout?
Answer
You can use std::stringstream for this:
#include <sstream>
#include <iostream>
int main(){
std::stringstream ss;
int a = 3;
ss<<"Hello, world! "<<a<<std::endl;
std::cout<<"Size was: "<<ss.str().size()<<std::endl;
std::cout<<ss.str()<<std::endl;
}
The above returns 16: 14 character for "Hello, world!", 1 character for the contents of the variable a, and one character from std::endl.